const int = int const?

C++

C++ Problem Overview


For example, is

int const x = 3;

valid code?

If so, does it mean the same as

const int x = 3;

?

C++ Solutions


Solution 1 - C++

They are both valid code and they are both equivalent. For a pointer type though they are both valid code but not equivalent.

Declares 2 ints which are constant:

int const x1 = 3;
const int x2 = 3;

Declares a pointer whose data cannot be changed through the pointer:

const int *p = &someInt;

Declares a pointer who cannot be changed to point to something else:

int * const p = &someInt;

Solution 2 - C++

Yes, they are the same. The rule in C++ is essentially that const applies to the type to its left. However, there's an exception that if you put it on the extreme left of the declaration, it applies to the first part of the type.

For example in int const * you have a pointer to a constant integer. In int * const you have a constant pointer to an integer. You can extrapolate this to pointer to pointers, and the English may get confusing but the principle is the same.

For another dicussion on the merits of doing one over the other, see my question on the subject. If you are curious why most folks use the exception, this FAQ entry of Stroustrup's may be helpful.

Solution 3 - C++

Yes, that is exactly the same. However, there is difference in pointers. I mean:

int a;

// these two are the same: pointed value mustn't be changed
// i.e. pointer to const value
const int * p1 = &a;
int const * p2 = &a;

// something else -- pointed value may be modified, but pointer cannot point
// anywhere else i.e. const pointer to value
int * const p3 = &a;

// ...and combination of the two above
// i.e. const pointer to const value
const int * const p4 = &a;

Solution 4 - C++

From "Effective C++" Item 21

char *p              = "data"; //non-const pointer, non-const data
const char *p        = "data"; //non-const pointer, const data
char * const p       = "data"; //const pointer, non-const data
const char * const p = "data"; //const pointer, const data

Solution 5 - C++

It is the same in meaning and validity.

As far as I know, const only get complex whenever it involves pointer.

int const * x;
int * const x; 

are different.

int const * x;
const int * x; 

are same.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser383352View Question on Stackoverflow
Solution 1 - C++Brian R. BondyView Answer on Stackoverflow
Solution 2 - C++T.E.D.View Answer on Stackoverflow
Solution 3 - C++ArchieView Answer on Stackoverflow
Solution 4 - C++YuanView Answer on Stackoverflow
Solution 5 - C++ttchongView Answer on Stackoverflow