What is the type of string literals in C and C++?

前端 未结 4 1741
感动是毒
感动是毒 2020-11-21 22:47

What is the type of string literal in C? Is it char * or const char * or const char * const?

What about C++?

4条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 23:41

    For various historical reasons, string literals were always of type char[] in C.

    Early on (in C90), it was stated that modifying a string literal invokes undefined behavior.

    They didn't ban such modifications though, nor did they make string literals const char[] which would have made more sense. This was for backwards-compatibility reasons with old code. Some old OS (most notably DOS) didn't protest if you modified string literals, so there was plenty of such code around.

    C still has this defect today, even in the most recent C standard.

    C++ inherited the same very same defect from C, but in later C++ standards, they have finally made string literals const (flagged obsolete in C++03, finally fixed in C++11).

提交回复
热议问题