开发者

What does L do?

What does this do?

const wchar_t *s = L"test";

If wchar_t is two bytes on my machine, then why should we tell the compiler that the string should be treated in a way that each element is long i.e, f开发者_如何学Pythonour bytes in size?


The L means that string is a string of wchar_t characters, rather than the normal string of char characters. I'm not sure where you got the bit about four bytes from.

From the spec section 6.4.5 String literals, paragraph 2:

A character string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in "xyz". A wide string literal is the same, except prefixed by the letter L.

And an excerpt from paragraph 5:

For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence; for wide string literals, the array elements have type wchar_t, and are initialized with the sequence of wide characters corresponding to the multibyte character sequence, as defined by the mbstowcs function with an implementation-defined current locale.


If in doubt, consult the standard (§6.4.5, String Literals):

A character string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in "xyz". A wide string literal is the same, except prefixed by the letter L.

Note that it does not indicate that each character is a long, despite being prefixed with the same letter as the long literal suffix.


L does not mean long integer when prefixing a string. It means each character in the string is a wide character.

Without this prefix, you are assigning a string of char to a wchar_t pointer, which would be a mismatch.


It indicates a string of wide characters, of type wchar_t.


If you don't know what that L does, then why are you making an assertive statement about each array element being long ("four bytes in size")? Where did that idea with the long come from?

That L has as much relation to long as it has to "leprechaun" - no relation at all. The L prefix means that the following string literal consists of wide characters, i.e. each character has wchar_t type.

P.S. Finally, it is always a good idea to use const-qualified pointers when pointing to string literals: const wchar_t *s = L"test";.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜