Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const int = int const?

Tags:

c++

For example, is

int const x = 3; 

valid code?

If so, does it mean the same as

const int x = 3; 

?

like image 997
user383352 Avatar asked Jul 14 '10 14:07

user383352


People also ask

Is const int the same as int const?

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.

What does const int * mean?

int const* is pointer to constant integer This means that the variable being declared is a pointer, pointing to a constant integer. Effectively, this implies that the pointer is pointing to a value that shouldn't be changed.

What does const int mean in C++?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. // constant_values1.cpp int main() { const int i = 5; i = 10; // C3892 i++; // C2105 }

How do you use const int?

Simple Use of 'const'One has to initialise it immediately in the constructor because, of course, one cannot set the value later as that would be altering it. For example, const int Constant1=96; will create an integer constant, unimaginatively called ' Constant1 ', with the value 96.


2 Answers

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; 
like image 78
Brian R. Bondy Avatar answered Sep 20 '22 04:09

Brian R. Bondy


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.

like image 29
T.E.D. Avatar answered Sep 17 '22 04:09

T.E.D.