Const Correctness Part 4

by Darren Collins
Sunday, 4 April 2004

I've saved this particular aspect of const correctness for its own short article, since it's a little less common and perhaps more controversial than others. I personally think it's a good idea, but I didn't want you to disregard everything else I had to say about const-correctness if you disagree with me on this one style issue. Even if you choose not to use this style, you'll still need to be aware of it if you ever need to read my code!

Last week's article talked about the placement of the const keyword in pointer or reference declarations. To refresh your memory, the following two pointer declarations mean exactly the same thing:

const int *p;
int const *p;      // My preference

But many people don't realise that both of the following declarations are also legal C++, and have identical meanings:

const int i = 1;
int const i = 1;   // My preference

I can't remember reading a single C++ tutorial, introductory book or training course that mentions the second form. I wasn't even sure it was legal when I first saw it (although it compiled OK), and had to check. It is, and there's a good reason for using it.

As I mentioned last week, the second declaration in both of the above examples allows you to read the variable's meaning from right to left. So, p is a pointer to a constant integer, and i is a constant integer. Easy!

I've got to admit, when I first discovered this idea of putting the const after the typename (instead of before it, like I was used to), I didn't like it. I thought it would be confusing to people who hadn't seen it before. But really, when you look at the second declaration of i above, what other interpretation could there be? You'd guess that i was a constant integer even if you'd never seen the const on the right of the typename before. And if they're still not sure and ask you, they'll learn a little more about C++ and good programming style!

So if you use this convention for declaring constants, you only have to use the right-to-left rule and you'll be able to figure out the meaning of any declaration involving const. Readability is always a worthwhile goal - after all, source code is written for humans to read, not computers.


Related Articles
- Links - C/C++
- Code Layout Styles
- Const Correctness Part 1
- Const Correctness Part 2
- Const Correctness Part 3
- Const Correctness Part 4
- Const Correctness Part 5
- Const Correctness Part 6

This site Copyright 1999-2005 Darren Collins.