Flipkart.com

II.8: When should the const modifier be used?

Answer:

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

(*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 wouldcompile but not run properly.Another reason is efficiency. The compiler might be able to make certain optimizations to the code generatedif it knows that a variable will not be changed.Any function parameter which points to data that is not modified by the function or by any function it callsshould declare the pointer a pointer to const. Function parameters that are passed by value (rather thanthrough a pointer) can be declared const if neither the function nor any function it calls modifies the data.In practice, however, such parameters are usually declared const only if it might be more efficient for thecompiler to access the data through a pointer than by copying it.

Reference:

II.7: Can a variable be both const and volatile?

II.14: When should a type cast not be used?

II.18: What is the benefit of using const for declaring constants?

No comments:

Post a Comment