I really can't understand what is the difference here
const int a = 1;
int const a = 1;
I know what constants are but the example above confuse me.
I really can't understand what is the difference here
const int a = 1;
int const a = 1;
I know what constants are but the example above confuse me.
There is no difference. Both are same.
Type specifiers are
void
,char
,short
,int
,long
,float
,double
,signed
,unsigned
,_Bool
,_Complex
,<struct-or-union-specifier>
,<enum-specifier>
, and<typedef-name>
.At least one type specifier shall be given in the declaration specifiers in each declaration, and in the specifier-qualifier list in each struct declaration and type name. Each list of type specifiers shall be one of the following multisets (delimited by commas, when there is more than one multiset per item); the type specifiers may occur in any order1, possibly intermixed with the other declaration specifiers.
1.Emphasis is mine
In this particular instance they are identical.
But, I think it's worth pointing out that the ordering does matter when it comes to pointers:
const int * a; // pointer to constant int
int const * a; // pointer to constant int
int * const a; // constant pointer to int
int const * const a; // constant pointer to constant int
In your case these statements are synonymous. Modifiers in C apply to the left specifier unless there is none. This makes more sense when you have pointers.
int const a;
defines a constant variable a
.
int const * a;
defines a modifiable pointer to a const variable.
int * const a;
defines a const pointer to a modifiable variable.
As others have said, your two code examples are the same.
An easy way to remember how to parse these kinds of expressions is:
const
appears next to (on either side) a typename, as in your example, the const
binds to the type name.const
binds to the first pointer to the left of it.So for example, int * const p
is a constant pointer to a non-constant int
, meaning that you can write to the int
using p
, but cannot change the value of p
.
One way of remembering whether a const
which is not next to a typename binds to the pointer on its left or right side is to consider the fact that expressions of the type int * const p
are legal, and so the const
in this expression has to bind to the pointer on the left. You do still need to remember that const
prefers typenames to pointers.