Wednesday, February 27, 2008

Anti-crash With const

You must use const at every opportunity. The const is your most powerful anti-crash weapon. An additional benefit is that it makes your code self-documenting. For instance, look at this:


const char *add2strings(const char *sz1, const char *sz2);

Such a declaration guarantee's that no matter what wierd things go on within the function, it can't harm the application programmer's two strings sz1 and sz2. If any memory corruption occurs, it will be to variables within the function's scope. This, of course, greatly reduces side effect bugs.

Furthermore, the declaration of the return pointer as const means that the application programmer can't "reach inside" the function to corrupt its scope. For instance, if the return value is a static array of 40 characters, if the return wasn't static the application programmer could do this:


char *pchName = add2strings("James", "Bond 007");
strcat(pchName, " jumps out of the plane and parachutes down");
cout << "I just corrupted an internal variable of add2strings. ";
cout << "Will I see this message?\n";
cout << "Will it crash later in the program? Who knows!\n";

Fortunately, because add2strings() returns a const pointer, you'll get a compiler error on this:

char *pchName = add2strings("Big galaxies", "Big stars");

Even if you declared pchName as a const char *, the moment you modified its contents with strcat() you'd get a compile error. The const keyword helps the programmer keep any errors localized, thus greatly reducing the likelihood of side-effect errors.

No comments: