Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const in C vs const in C++

Tags:

c++

c

constants

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

like image 704
Sergii Avatar asked May 22 '11 11:05

Sergii


People also ask

What is a const in C?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

Is #define the same as const?

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

What is the difference between int * const C and const int * C?

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.

Is const faster in C?

No, const does not help the compiler make faster code.


1 Answers

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.

like image 188
Johannes Schaub - litb Avatar answered Sep 21 '22 17:09

Johannes Schaub - litb