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?
const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object. const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.
As a common rule, it is very often considered a bad practice to use const_cast<>() in C++ code as it reveals (most of the time) a flaw in the design.
const_cast is safe only if you're casting a variable that was originally non- const . For example, if you have a function that takes a parameter of a const char * , and you pass in a modifiable char * , it's safe to const_cast that parameter back to a char * and modify it.
In C++, string literals are stored in arrays of const char , so that any attempt to modify the literal's contents will trigger a diagnostic at compile time. As Christian points out, the const keyword was not originally a part of C.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With