Skip to content

Instantly share code, notes, and snippets.

@burczyk
Created January 28, 2014 13:46
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save burczyk/8667937 to your computer and use it in GitHub Desktop.
Save burczyk/8667937 to your computer and use it in GitHub Desktop.
const int VS int const
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 constant
s++; // Can do because the pointer isn't constant
*t = 'A'; // Can do because the char isn't constant
t++; // Can't do because the pointer is constant
@patrickkon
Copy link

Thanks for the quick explanation.

@yozaam
Copy link

yozaam commented May 25, 2020

This is great! Reading it backwards makes it very simple

Noob question: can I do: const char *const s ?

@PrateekJoshi
Copy link

This is great! Reading it backwards makes it very simple

Noob question: can I do: const char *const s ?

Yes you can, in that case you can't do s++ as your pointer is also a constant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment