I'm Michael Suodenjoki - a software engineer living in Kgs. Lyngby, north of Copenhagen, Denmark. This is my personal site containing my blog, photos, articles and main interests.

Updated 2011.01.23 15:37 +0100

 

C++ Const Placement

Recently I had a discussion with a C++ developer about how to use the const keyword in C++, for example:

const int i; // this way?
int const i; // or this way?

Both ways are fully valid and means the same thing - namely the declaration of a constant integer variable. So it seems to be a matter of personal style. The developer preferred the second style while I was used to the first style. I found it more readable and less confusing.

However matters becomes more blurry when dealing with pointers. For constant pointers the rule is that the pointer always comes after the const keyword. For example (and here it's nice to know that types are actually best read from right to left):

const int* i; // ok, pointer to integer constant
const* int i; // not ok, integer to pointer constant!
int* const i; // ok, constant pointer to integer
int const* i; // ok, pointer to constant integer

On the inventor of C++. Bjarne Stroustrup's  website you can find a similar explanation.