Is char *p=”abc” valid in C++?

The question

Is the declaration char *p = “abc” valid in C++?
In other words: is it legal in C++ to create a non-const char pointer that points to a string literal?

The answer

As a general rule, in programming languages C and C++, there’s no implicit conversion from const to non-const.
However, in C language, “abc” which is a string literal, is of type array of (non-constat) chars. So, a declaration of this kind is perfect legal in C:

C++ language, which is derived from C, preserved for a while the backward compatibility to legacy code written in C.
So, even if in C++ a string literal is of type array of const char, the C++ standards, including ISO/IEC 14882:2003 (aka C++03), still consider the above declaration as legal (although, “deprecated”).

C++03
char* p = “abc”; // valid in C, deprecated in C++

However, that has been changed in the new standard, ISO/IEC 14882:2011 (aka C++11), that clearly states:

C++11
char* p = “abc”; // valid in C, invalid in C++

Conclusion

The above declaration is not valid for C++ compilers which are C++11 standard-compliant, but may be valid for the other ones.

Resources

  • ISO/IEC 14882:2003 Information technology — Programming languages — C++
    (Annex C – Compatibility)
  • ISO/IEC 14882:2011 Information technology — Programming languages — C++
    (Annex C – Compatibility)

See also

 

Leave a Reply