Flipkart.com

II.4: What is a const pointer?

Answer:
The access modifier keyword const is a promise the programmer makes to the compiler that the value of avariable will not be changed after it is initialized. The compiler will enforce that promise as best it can by notenabling the programmer to write code which modifies a variable that has been declared const.
A “const pointer,” or more correctly, a “pointer to const,” is a pointer which points to data that is const(constant, or unchanging).
A pointer to const is declared by putting the word const at the beginning of thepointer declaration. This declares a pointer which points to data that can’t be modified. The pointer itselfcan be modified.
The following example illustrates some legal and illegal uses of a const pointer:

const char *str = “hello”;
char c = *str /* legal */str++;/* legal */
*str = ‘a’; /* illegal */
str[1] = ‘b’;/* illegal */

The first two statements here are legal because they do not modify the data that str points to. The next twostatements are illegal because they modify the data pointed to by str.Pointers to const are most often used in declaring function parameters. For instance, a function that countedthe number of characters in a string would not need to change the contents of the string, and it might bewritten this way:

my_strlen(const char *str){int count = 0;
while (*str++)
{
++;
}
return count;
}
Note that non-const pointers are implicitly converted to const pointers when needed, but const pointersare not converted to non-const pointers. This means that my_strlen() could be called with either a constor a non-const character pointer.
Reference:
II.7: Can a variable be both const and volatile?
II.8: When should the const modifier be used?
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