Why Conversion from String Literal to 'char*' is Valid in C but Invalid in C
In § C.1.1 of the C 11 Standard (ISO/IEC 14882:2011), the assignment char* p = "abc" is declared invalid. However, this conversion is still valid in C. Why is this the case?
Implicit Conversion Deprecated in C
In C versions up to C 03, the conversion from a string literal to 'char*' was valid, albeit deprecated. String literals should be treated as 'char const *', as their contents cannot be modified without undefined behavior.
Explicit Conversion Remains Valid
Although the implicit conversion was deprecated in C 11, an explicit conversion remains valid. To make the code compile, a cast can be added: char* p = (char*)"abc".
Disadvantages of Casting
However, this explicit conversion does not "fix" the code. It simply allows the compiler to accept the assignment. The potential issues with modifying the string literal still exist.
Solution: Use the Correct Type
The proper way to handle string literals is to use the correct type, 'char const *': char const *p = "abc". This approach is both valid and safe in both C and C .
Justification in C
The conversion remains valid in C because a significant amount of existing code relies on it. Breaking this code without proper warning was considered undesirable by the standard committees.
The above is the detailed content of Why Are String Literal to `char*` Conversions Valid in C but Invalid in C ?. For more information, please follow other related articles on the PHP Chinese website!