Search code examples
c++c++11string-literalsconst-cast

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


I'm looking at some sample code for an API I'm about to start using. The following pattern has me a bit confused:

char* str;
str = const_cast<char*>("Hello World");

printf("%s ", str);

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

Note that printf takes const char*. Is there any reasonable purpose for this convoluted conversion? The authors of this code are applying lots of performance oriented tricks elsewhere, but there is no explanation for what's going on here.

My instinct is to change this code to:

const char* str;
str = "Hello World";

printf("%s ", str);

Am I missing something?


Solution

  • A string literal is a non-const char[N] in C, and a const char[N] in C++. Earlier versions of the C++ standard made special allowance for a const string literal to be assigned to a non-const char* for backwards compatibility with C. However, this behavior was deprecated in C++03 and is now illegal in C++11 without an explicit cast, such as the one shown.

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