To understand why this frustrating warning occurs, let's suppose that the warning
didn't occur and consider this code:
1 2 3 4 5 6 7 8 9
|
void foo(char *cp) {
cp[0] = 'B'; // modify the first character
}
int main()
{
foo("Hello World");
std::cout << "Hello World" << std::endl;
}
|
The compiler might store
"Hello World"
in read-only memory. Maybe it's compiling for a small device like a hand-held calculator where there is 128K of ROM but only 2K of RAM.
"Hello World"
is a string literal after all - it won't change. But now
foo()
tries to change it. Bam - the program tries to modify read-only memory and crashes.
Next let's consider what happens if you store
"Hello World"
in RAM. There's no reason that each instance of
"Hello World"
must be separate (I'm pretty sure this is in the standard but someone with more knowledge would have to say). So you call
foo("Hello World")
and it changes the string to "Bello world". Then
main()
tries to print "Hello World" and ends up printing "Bello World" instead!! Good luck finding THAT bug. :)
So string literals are
const
. You can't modify them because Bad Things will happen if you do. A function that takes
char *
as a parameter is telling the compiler that it might modify the string, so the compiler doesn't allow that.