Home > Backend Development > C++ > Why Are String Literal to `char*` Conversions Valid in C but Invalid in C ?

Why Are String Literal to `char*` Conversions Valid in C but Invalid in C ?

Mary-Kate Olsen
Release: 2024-12-15 12:25:15
Original
296 people have browsed it

Why Are String Literal to `char*` Conversions Valid in C but Invalid in C  ?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template