Alex Rivera | Logout

Are string literals const?

Asked 2010-12-20T19:31:26.307
33

Both GCC and Clang do not complain if I assign a string literal to a char*, even when using lots of pedantic options (-Wall -W -pedantic -std=c99):

char *foo = "bar";

while they (of course) do complain if I assign a const char* to a char*.

Does this mean that string literals are considered to be of char* type? Shouldn't they be const char*? It's not defined behavior if they get modified!

And (an uncorrelated question) what about command line parameters (ie: argv): is it considered to be an array of string literals?

Edit
Report

2 Answers

7

Using -Wwrite-strings option you will get:

warning: initialization discards qualifiers from pointer target type

Irrespective of that option, GCC will put literals into read-only memory section, unless told otherwise by using -fwritable-strings (however this option has been removed from recent GCC versions).

Command line parameters are not const, they typically live on the stack.

answered 2010-12-20T19:40:23.963
2

Johannes' answer is correct concerning the type and contents. But in addition to that, yes, it is undefined behavior to modify contents of a string literal.

Concerning your question about argv:

The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.

answered 2010-12-20T19:40:08.307

Your Answer