What is the datatype of string literal in C++?

六月ゝ 毕业季﹏ 提交于 2019-12-17 06:43:21

问题


I'm confused about the datatype of a string literal. Is it a const char * or a const char?


回答1:


It is a const char[N] (which is the same thing as char const[N]), where N is the length of the string plus one for the terminating NUL (or just the length of the string if you define "length of a string" as already including the NUL).

This is why you can do sizeof("hello") - 1 to get the number of characters in the string (including any embedded NULs); if it was a pointer, it wouldn't work because it would always be the size of pointer on your system (minus one).




回答2:


"Hello world" is const char[12] (eleven characters plus '\0' terminator).

L"Hello world" is const wchar_t[12].

And since C++14, "Hello world"s is std::string.

Also note the u8"", u"" and U"" string literal notations added by C++11, which specify UTF-8, UTF-16 and UTF-32 encoding, respectively. The encoding of non-qualified string literals (i.e. "" and L"") is (and always was) implementation-defined.



来源:https://stackoverflow.com/questions/12517983/what-is-the-datatype-of-string-literal-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!