The given code compiles in C but fails in C++.
int main()
{
const int x; /* uninitialized const compiles in C but fails in C++*/
}
What is the rationale and the reason behind the change from C to C++?
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.
The difference is that #define is processed by the preprocessor doing what amounts to simple text replacement. Const values defined like this are not visible for the actual compiler, while a variable defined with the const modifier is an actual typed "variable" (well not really that variable).
const int * And int const * are the same. const int * const And int const * const are the same. If you ever face confusion in reading such symbols, remember the Spiral rule: Start from the name of the variable and move clockwise to the next pointer or type. Repeat until expression ends.
No, const does not help the compiler make faster code.
See the spec, in the compatibility appendix C.1.6:
7.1.6 [see also 3.5]
Change: const objects must be initialized in C++ but can be left uninitialized in C
Rationale: A const object cannot be assigned to so it must be initialized to hold a useful value.
Effect on original feature: Deletion of semantically well-defined feature.
Difficulty of converting: Semantic transformation.
How widely used: Seldom.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With