The (pre)compiler knows that symbolic constants won't change. It substitutes the value for the constant at compile time. If the "constant" is in a variable, it usually can't figure out that the variable will never change value. In consequence, the compiled code has to read the value from the memory allocated to the variable, which can make the program slightly slower and larger.
In C++, you can declare a variable to be const
, which tells the compiler pretty much the same thing. This is why symbolic constants are frowned upon in C++.
Note, however, that in C (as opposed to C++) a const int
variable is not a constant expression. Therefore, trying to do something like this:
const int a = 5;
int b[a] = {1, 2, 3, 4, 5};
will work in C++ but will get you a compilation error in C (assuming b
was supposed to be a statically bound array).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…