Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 732
Drew Noakes Avatar asked Oct 21 '14 17:10

Drew Noakes


People also ask

What is the point of const_cast?

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.

Is const_cast good practice?

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.

Is const_cast safe?

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.

Is a string literal a const char *?

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.


1 Answers

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.

like image 103
Remy Lebeau Avatar answered Oct 29 '22 17:10

Remy Lebeau