'const int' vs. 'int const' as function parameters in C++ and C 'const int' vs. 'int const' as function parameters in C++ and C c c

'const int' vs. 'int const' as function parameters in C++ and C


The trick is to read the declaration backwards (right-to-left):

const int a = 1; // read as "a is an integer which is constant"int const a = 1; // read as "a is a constant integer"

Both are the same thing. Therefore:

a = 2; // Can't do because a is constant

The reading backwards trick especially comes in handy when you're dealing with more complex declarations such as:

const char *s;      // read as "s is a pointer to a char that is constant"char c;char *const t = &c; // read as "t is a constant pointer to a char"*s = 'A'; // Can't do because the char is constants++;      // Can do because the pointer isn't constant*t = 'A'; // Can do because the char isn't constantt++;      // Can't do because the pointer is constant


const T and T const are identical. With pointer types it becomes more complicated:

  1. const char* is a pointer to a constant char
  2. char const* is a pointer to a constant char
  3. char* const is a constant pointer to a (mutable) char

In other words, (1) and (2) are identical. The only way of making the pointer (rather than the pointee) const is to use a suffix-const.

This is why many people prefer to always put const to the right side of the type (“East const” style): it makes its location relative to the type consistent and easy to remember (it also anecdotally seems to make it easier to teach to beginners).


There is no difference. They both declare "a" to be an integer that cannot be changed.

The place where differences start to appear is when you use pointers.

Both of these:

const int *aint const *a

declare "a" to be a pointer to an integer that doesn't change. "a" can be assigned to, but "*a" cannot.

int * const a

declares "a" to be a constant pointer to an integer. "*a" can be assigned to, but "a" cannot.

const int * const a

declares "a" to be a constant pointer to a constant integer. Neither "a" nor "*a" can be assigned to.

static int one = 1;int testfunc3 (const int *a){  *a = 1; /* Error */  a = &one;  return *a;}int testfunc4 (int * const a){  *a = 1;  a = &one; /* Error */  return *a;}int testfunc5 (const int * const a){  *a = 1;   /* Error */  a = &one; /* Error */  return *a;}