Learning C++ const Constants from Scratch: Definitions and Usage Scenarios

In C++, we often need to define fixed and unchangeable values, such as the mathematical constant π (pi), the number of days in a week, etc. Once these values are determined, they will not change. In such cases, we can use the const keyword to define them, which we call const constants.

一、What are const Constants?

Imagine if you encounter “π ≈ 3.14159” in a math problem. This value never changes, like a “fixed box” that can only be filled once and cannot be modified. In C++, the role of const constants is similar: once defined, their values cannot be modified. This prevents errors caused by accidental modifications to critical data in the code.

Compared with ordinary variables (which can be modified at any time, e.g., int a = 5; a = 10;), const constants are “locked” after definition. Any attempt to modify them will result in a compiler error.

二、How to Define const Constants?

The syntax for defining a const constant is very simple:
const 数据类型 常量名 = 初始值;

For example:

const int age = 18;        // Define an integer constant 'age' with value 18
const double pi = 3.14159; // Define a double-precision floating-point constant 'pi'

Note: The position of const can be flexible, but it is usually placed before the type (e.g., const int). Additionally, const constants must be initialized at the time of definition, otherwise the compiler will report an error.

三、Core Features of const Constants

  1. Unmodifiable:
    This is the most core feature of const. If you try to modify a const constant, the compiler will directly report an error.
    Error example:
   const int a = 5;
   a = 10; // Compilation error! Cannot modify a const constant
  1. Must Be Initialized:
    const constants must be assigned a value at the time of definition; otherwise, they will fail to compile.
    Error example:
   const int b; // Error! No initialization
   b = 10;      // Even if you assign here, it will not pass compilation
  1. Scope Rules:
    The scope of a const constant is the same as that of an ordinary variable. If defined inside a function, it can only be used within that function; if defined globally (outside all functions), it can be accessed throughout the entire program.

四、Common Use Cases for const Constants

  1. Protect Critical Data
    When a value is a “fixed rule” in the program, using const to define it prevents accidental modifications. For example:
   const int max_students = 50; // Maximum 50 students in a class (cannot be changed arbitrarily)
   const double PI = 3.14159;   // Pi, fixed and unchangeable
  1. Improve Code Readability
    Using const constants instead of “magic numbers” (hard-coded numbers) makes the code clearer. For example:
   // Unclear: Directly writing numbers makes it hard to know what "10" represents
   for(int i=0; i<10; i++){...}  

   // Clear: "loop_times" makes it obvious the loop runs 10 times
   const int loop_times = 10;  
   for(int i=0; i<loop_times; i++){...}  
  1. As Array Lengths
    The length of a regular array must be a constant determined at compile time, and const constants exactly meet this requirement. For example:
   const int arr_size = 5;  // Define array length as 5
   int scores[arr_size];    // Valid! Array length is a constant
  1. Optimize Function Parameters (Advanced)
    If a function parameter is a const reference, it avoids copying large objects and improves efficiency. For example:
   void print_info(const string &name){ // const reference parameter to avoid copying
       cout << "Name: " << name << endl;
   }

Here, const ensures the function will not modify the value of name, and the reference (&) avoids the overhead of copying the string.

五、const Constants vs #define (Simple Comparison)

In C++, you may have heard of #define (a preprocessing directive). Both const and #define can define constants, but const is safer and more reliable:
- #define: Performs “text substitution” without type checking, which may lead to logical errors. For example, #define PI 3.14 will directly replace all occurrences of PI with 3.14 during preprocessing. If subsequent calculations involve integer types, precision issues may arise.
- const: A C++ keyword with type checking, making it safer. For example, const double PI = 3.14 ensures the compiler strictly checks the type and avoids accidental substitutions.

六、Precautions

  1. Must Be a Compile-Time Constant:
    The value of a const constant must be determinable at compile time (e.g., literals, fixed expressions). It cannot be assigned using runtime variables.
    Error example:
   int x = 5;
   const int y = x; // Error! The value of 'x' is determined at runtime, so it cannot initialize a const constant
  1. Scope Limitations:
    The scope of a const constant is determined by its definition location. A global const constant (defined outside functions) can be accessed by the entire program, while a local const constant (defined inside a function) is only valid within that function.

Summary

const constants are an important tool in C++ for protecting data, improving code readability, and enhancing security. Remember: Use const to define fixed values, making your code more reliable and clearer. From today onward, try replacing magic numbers with const constants in your code, and you’ll find that code maintenance becomes much simpler!

Xiaoye