The const
qualifier means that a variable/pointer defined as const
may not be changed by your program and it will receive its value either from an explicit initialization or by a hardware-dependent means.
A pointer that is defined as const
in the parameter declarations, the function code will not modify what it points to. Basically, you can use the pointer and it pretty much functions as a "read-only".
For example:-
void foo(const char *x)
{
while(*x)
{
if(*x==' ') cout << '-'; //printing - when a space is encountered
else cout << *x;
x++;
}
}
The above function is fine and won't show any errors. But if foo had any thing that could change the string passed. say a function that replaces spaces with $. Not print $ but changing it to $. Something like this:-
void foo(const char *x)
{
while(*x)
{
if(*x==' ') *x = '$'; //printing - when a space is encountered
else cout << *x;
x++;
}
}
then it would not compile i.e. an assignment error to a read-only memory location.