I have just read article “Please declare your variables as const” by Bartłomiej Filipek. It argues that declaring your variables const is beneficial for reasons other than performance. In particular, it can help find bugs in your code. Now, let me illustrate this claim by showing how the const could help find the bug from my previous post.

Let’s see the buggy code again:

void process_names() { const char * fileName = "contents.txt"; const char * foundName = 0; // to be assigned to later Names names = parse_file(foundName); foundName = find(names); // ... }

This program is expected to open file contents.txt , read names from it; then find a desired name, and do something with it. But the program will not do it, because I have a bug in this code. Accidentally, I have passed the wrong pointer to function parse_file . I confused them because names were so similar (I didn’t notice that my IDE suggested the wrong name in the hint); the types happened to match…

Now, let’s see how the situation changes when I apply the principle “mark your variables as const, wherever possible”:

void process_names() { const char * const fileName = "contents.txt"; const char * const foundName = 0; // to be assigned to later Names names = parse_file(foundName); foundName = find(names); // ... }

I have annotated the two pointers as const . With pointers, this is a bit tricky: you have to remember on each side of the pointer to put it.

Now, my program fails to compile: I am trying to assign an address to a constant pointer. Thus, I am forced to apply another principle: “declare your variables as local as possible”. I will move the the declaration of foundName down to line 7:

void process_names() { const char * const fileName = "contents.txt"; Names names = parse_file(foundName); const char * const foundName = find(names); // ... }

Now, I get another error: I am reading from variable foundName before it is declared. But I never wanted to read it there! And now, the compiler has brought my attention to the misused variable. Only because I decided to make my variables const.

The connection is somewhat accidental; but for some subtle bugs, such accidental discoveries might be the best option. The more opportunities you will make for these “accidents”, the more chances you have of finding the bug.