next up previous
Next: Static object initialization order Up: C++/C Previous: C++/C

String const

for a C++ code
char* foo = ``hello world'';
foo[0] = 'g';
the code is legal, but the running result is undefined, that means it can seg fault or run successfully. It depends on the c++ compiler; The c++ stand says

Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined. The effect of attempting to modify a string literal is undefined.

Why C++ doesn't give compiler error is because of the compatibility to C, that means the correct C++ syntax should be const char* foo = ``hello world'';

BTW , the code is working if it is compiled by cc; more detail from http://www.possibility.com/Cpp/const.html



Wei Lu 2007-11-06