简体   繁体   中英

Redefine const char* in C

Assume the following code in C :

const char * string = "123";
if(condition) string = "somethingelse";

printf("%s\n", string);

Although I know that it is working (at least with gcc on x86_64 ) and no compiler warning are being generated, I'm wondering if this is something I should be doing like this or if there is a better alternative.

Note that this question is not a duplicate of Difference between char* and const char*? as it explicitly asks if a redefinition of the content of the variable is good practice. The other question is asking for the difference between char* and const char* and the accepted answer does only provide the answer if one already knows what the assignment of another value means. This was unclear to me and is an essential of this question.

It's fine, the pointer is just being re-assigned a new value, which is also of type const char * .

If you wanted the pointer itself to stay constant too (which helps with clarity in my opinion), you can do it:

const char * const string = condition ? "somethingelse" : "123";

This makes string have the type "constant pointer to constant char ", so you cannot re-assign it (or change the data it's pointing at, of course).

In C if you are writting this:

const char* string = "123";

Then string is a pointer pointed to a const char array. The pointer itself is not a constant, so you can modify the pointer.

If you want to make the pointer as a const:

const char* const string = "123";

Then you can't change it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM