Search code examples
c++cconstants

const in C vs const in C++


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++?


Solution

  • 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.