⬆⬆⬆ Follow 【Pai Zhi Tang】 for valuable content 📚 Math Engine, Core Programming, Algorithm Foundation 🔥 AI Application Hotspots, Reconstruction in Various Industries
💡 Introduction to the Informatics Olympiad Competition System
In C++ programming, constants and variables are among the most fundamental and important concepts. They are used to store data needed in the program, but they differ significantly in usage, characteristics, and application scenarios. Below, I will detail their naming rules, definition methods, and roles in the program.
1. Variables
1. Concept of Variables
A variable is a named memory location used to store data in a program, and its value can change during program execution.
2. Definition of Variables
data_type variable_name [= initial_value];
Example:
int age; // Declare an integer variable
double price = 19.99; // Declare and initialize a double variable
char grade = 'A'; // Declare and initialize a character variable
3. Naming Rules for Variables
- Valid Characters: Letters (a-z, A-Z), digits (0-9), and underscores (_)
- Starting Character: Must start with a letter or underscore (cannot start with a digit)
- Case Sensitivity:
<span>myVar</span>and<span>myvar</span>are different variables - Length Limit: Theoretically unlimited, but the first 31 characters must be unique (some compilers may have different limits)
- Cannot Use Keywords: Keywords like
<span>int</span>,<span>double</span>,<span>class</span>cannot be used as variable names
4. Good Naming Practices for Variables
- Use meaningful names (e.g.,
<span>studentCount</span>instead of<span>s</span>) - Adopt a consistent naming style:
- Camel Case:
<span>studentName</span>,<span>totalAmount</span> - Underscore Style:
<span>student_name</span>,<span>total_amount</span> - Avoid using single characters (except for loop counters like
<span>i</span>,<span>j</span>,<span>k</span>) - Boolean variables typically start with
<span>is</span>,<span>has</span>,<span>can</span>:<span>isValid</span>,<span>hasPermission</span>
5. Functions of Variables
- Store data that needs to change during program execution
- Improve code readability (through meaningful variable names)
- Facilitate data management and operations
- Store intermediate results in algorithms
2. Constants
1. Concept of Constants
A constant is a fixed value in a program that cannot be modified once defined during program execution.
2. Definition Methods for Constants
(1) Using the <span>const</span> keyword
const data_type constant_name = value;
Example:
const double PI = 3.14159;
const int MAX_SIZE = 100;
(2) Using the <span>#define</span> preprocessor directive (C style, not recommended for priority use in C++)
#define constant_name value
Example:
#define PI 3.14159
(3) Using <span>constexpr</span> introduced in C++11 (compile-time constant)
constexpr data_type constant_name = value;
Example:
constexpr int ARRAY_SIZE = 256;
3. Naming Rules for Constants
- Usually use all uppercase letters, with words separated by underscores
- Other rules are similar to variable naming. Example:
const int MAX_CONNECTIONS = 10;
const double TAX_RATE = 0.08;
4. Functions of Constants
- Improve code readability and maintainability (magic numbers → meaningful constant names)
- Prevent accidental modification of important values
- Facilitate centralized management of fixed values used in the program
- Used in cases requiring constant expressions, such as array sizes, case labels, etc.
3. Comparison of Variables and Constants
| Characteristic | Variable | Constant |
|---|---|---|
| Value Mutability | Can change | Cannot change after definition |
| Definition Keyword | No special keyword | <span>const</span>, <span>constexpr</span>, <span>#define</span> |
| Naming Convention | Usually lowercase or camel case | Usually all uppercase with underscores |
| Memory Allocation | Runtime allocation | Compile-time constants may be directly replaced |
| Usage Scenario | Store changing data | Store fixed values |
4. Scope and Lifetime
1. Local Variables/Constants
- Defined within a function or code block
- Visible only within the block where they are defined
- Lifetime starts from the definition until the block ends
void myFunction() {
int localVar = 10; // Local variable
const int LOCAL_CONST = 20; // Local constant
// ...
} // localVar and LOCAL_CONST lifetime ends here
2. Global Variables/Constants
- Defined outside all functions
- Visible from the definition point to the end of the file
- Lifetime lasts for the entire program execution
#include <iostream>
int globalVar = 50; // Global variable
const int GLOBAL_CONST = 100; // Global constant
int main() {
std::cout << globalVar << std::endl;
std::cout << GLOBAL_CONST << std::endl;
return 0;
}
3. Static Variables
- Declared using the
<span>static</span>keyword - Lifetime lasts for the entire program execution
- Scope is still limited to the block where it is defined
void counter() {
static int count = 0; // Initialized only once
count++;
std::cout << count << std::endl;
}
5. Best Practice Recommendations
- Use constants whenever possible: Prefer using
<span>const</span>unless the value truly needs to change - Avoid global variables: Use local variables unless necessary; global variables can make code hard to maintain
- Initialize variables: Try to initialize variables when defining them to avoid undefined behavior
- Choose scope wisely: Define variables in the smallest possible scope
- Use meaningful names: Make the code self-documenting
- Pay attention to type matching: Ensure the values assigned to variables/constants are compatible with the declared type
6. Example Program
#include <iostream>
// Global constants
const int MAX_ATTEMPTS = 3;
const double TAX_RATE = 0.075;
// Function declaration
double calculateTotal(double price, int quantity);
int main() {
// Local variables
double itemPrice = 0.0;
int itemQuantity = 0;
std::cout << "Enter item price: ";
std::cin >> itemPrice;
std::cout << "Enter quantity: ";
std::cin >> itemQuantity;
// Call function to calculate total price
double total = calculateTotal(itemPrice, itemQuantity);
std::cout << "Total cost (including tax): $" << total << std::endl;
return 0;
}
double calculateTotal(double price, int quantity) {
// Local constant
const double DISCOUNT_RATE = 0.1;
// Local variable
double subtotal = price * quantity;
// Apply discount if quantity exceeds 5
if (quantity > 5) {
subtotal -= subtotal * DISCOUNT_RATE;
}
// Calculate total price including tax
double total = subtotal * (1 + TAX_RATE);
return total;
}


-
Detailed introduction to the National Youth Informatics Olympiad Competition System
-
What benefits does participating in the Informatics Olympiad bring to children?
-
Detailed introduction to the National Youth Informatics Olympiad Competition System: CSP-J
-
Detailed introduction to the National Youth Informatics Olympiad Competition System: CSP – S
-
Detailed introduction to the National Youth Informatics Olympiad Competition System: NOIP