Is there any reason to use const_cast for a string literal in this code?

I am looking for sample code for an API that I am going to start using. The following template confuses me a bit:

char* str; str = const_cast<char*>("Hello World"); printf("%s ", str); 

(there is actually a huge case statement in which str is assigned in each case.)

Note that printf accepts const char* . Is there a reasonable purpose for this minimized transformation? The authors of this code apply many performance-oriented tricks elsewhere, but there is no explanation for what happens here.

My instinct is to change this code to:

 const char* str; str = "Hello World"; printf("%s ", str); 

Did I miss something?

+5
source share
2 answers

The string literal is non-constant char[N] in C and a const char[N] in C ++. Earlier versions of the C ++ standard specifically considered the string literal const , which must be bound to a non-constant char* for backward compatibility with C. However, this behavior was deprecated in C ++ 03 and is now illegal in C ++ 11 without explicit casting. for example, shown.

If you are only interested in C ++ 11, you should change str to const char* . Otherwise, you can use the cast for backward compatibility.

+3
source

The only possible reason might be that printf requires char* in some specific implementation. Which, after some research, seems to be wrong. On the other hand, having a pointer to a non-const char pointing to a string literal is dangerous because modifying the string literal causes undefined behavior. If it works without a throw, there is no reason for it to be there, and you should change it right now.

+2
source

Source: https://habr.com/ru/post/1205212/


All Articles