Showing posts with label const modifier. Show all posts
Showing posts with label const modifier. Show all posts

Thursday, 17 November 2011

When should the const modifier be used?

There are several reasons to use const pointers. First, it allows the compiler to catch errors in which code accidentally changes the value of a variable, as in

while (*str = 0) /* programmer meant to write *str != 0 */
{


/* some code here */
str++;


}


in which the = sign is a typographical error. Without the const in the declaration of str, the program would compile but not run properly.

Another reason is efficiency. The compiler might be able to make