3

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.

DRON
  • 93
  • 1
  • 5
  • possible duplicate of [What is the difference between char \* const and const char \*?](http://stackoverflow.com/questions/890535/what-is-the-difference-between-char-const-and-const-char) – sashoalm Dec 05 '13 at 14:01
  • 2
    @sashoalm; It is not the same question. That's a completely different issue. – haccks Dec 05 '13 at 14:09

4 Answers4

7

There is no difference. Both are same.

Draft n1570: 6.7.2 Type specifiers:

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

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
7

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
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

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.

Sergey L.
  • 21,822
  • 5
  • 49
  • 75
0

As others have said, your two code examples are the same.

An easy way to remember how to parse these kinds of expressions is:

  • If the const appears next to (on either side) a typename, as in your example, the const binds to the type name.
  • Otherwise, the 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.

Andrey Mishchenko
  • 3,986
  • 2
  • 19
  • 37