DEV Community

Cover image for ISO C++ forbids converting a string constant to char*

ISO C++ forbids converting a string constant to char*

smithmchael550 profile image smithmchael550 ・1 min read

char* p = "abc";


In the given line of code, we defined an array of char* objects. We initialize pointers with string constants. But the compiler shows error and as the error explains itself, converting a string constant not allowed in C++. There is no extra explanation for this error because it is a rule of C++ and as we all know C++ is a very sensitive programming language as both “a” and “A” have different meanings along with memory allocation.

If you have use C instead of C++ a lot, then you may be wondering why is a conversion from string constant to char* is valid in C but invalid in C++?
Till C++03, line of code given above was valid, but used a criticize implicit conversion i.e., a string constant should be treated as of type char const *, because you can't modify its contents. And if you modify its contents, there will be undefined behaviour.
When C++11 comes to the real world of programming, the implicit conversion, which used to be criticized, was officially removed, so code that depends on it should no longer compile.



How to resolve this problem?

As we discuss why converting a string literal to const char* is not allowed, so instead of doing this, we can declare an array of const char*. If we don’t modify the strings pointed by the array, this should not be a problem.

Discussion (1)

dynamicsquid profile image

Or use std::string :)

Forem Open with the Forem app