Type of a C++ string literal

后端 未结 3 953
攒了一身酷
攒了一身酷 2020-12-19 10:28

Out of curiosity, I\'m wondering what the real underlying type of a C++ string literal is.

Depending on what I observe, I get different results.

A typeid tes

相关标签:
3条回答
  • 2020-12-19 10:31

    First off, the type of a C++ string literal is an array of n const char. Secondly, if you want to initialise a wchar_t with a string literal you have to code:

    wchar_t* s = L"hello"
    
    0 讨论(0)
  • 2020-12-19 10:50

    The type of a string literal is indeed const char[SIZE] where SIZE is the length of the string plus the null terminating character.

    The fact that you're sometimes seeing const char* is because of the usual array-to-pointer decay.

    But I don't see how it could be const char * as the following line is accepted by VS12: char* s = "Hello";

    This was correct behaviour in C++03 (as an exception to the usual const-correctness rules) but it has been deprecated since. A C++11 compliant compiler should not accept that code.

    0 讨论(0)
  • 2020-12-19 10:54

    The type of a string literal is char const[N] where N is the number of characters including the terminating null character. Although this type does not convert to char*, the C++ standard includes a clause allowing assignments of string literal to char*. This clause was added to support compatibility especially for C code which didn't have const back then.

    The relevant clause for the type in the standard is 2.14.5 [lex.string] paragraph 8:

    Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

    0 讨论(0)
提交回复
热议问题