C++中的L前缀到底是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13087219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:56:36  来源:igfitidea点击:

What exactly is the L prefix in C++?

c++stringwidestring

提问by user965369

I understand what it does: specifies a string literal as a const wchar_t *(wide character string) instead of const char *(plain old characters), but how is it actually defined?

我理解它的作用:将字符串文字指定为const wchar_t *(宽字符串)而不是const char *(纯旧字符),但它实际上是如何定义的?

Is it a macro of some sort? Is it an operator for GCC compilers? What isit?

它是某种宏吗?它是 GCC 编译器的运算符吗?什么它?

回答by Kerrek SB

The literal prefixes are a part of the core language, much like the suffixes:

文字前缀是核心语言的一部分,很像后缀:

'a'    // type: char
L'a'   // type: wchar_t

"a"    // type: char[2]
L"a"   // type: wchar_t[2]
U"a"   // type: char32_t[2]

1      // type: int
1U     // type: unsigned int

0.5    // type: double
0.5f   // type: float
0.5L   // type: long double

Note that wchar_thas nothingto do with Unicode. Here is an extended rant of mineon the topic.

请注意,wchar_t没有做使用Unicode。这是对这个主题的扩展咆哮

回答by Luchian Grigore

It's called an encoding prefix:

它被称为编码前缀

2.14.5 String literals [lex.string]

2.14.5 字符串文字 [lex.string]

string-literal:
| encoding-prefixopt" s-char-sequenceopt"
| encoding-prefixoptR raw-string
encoding-prefix:
| u8
| u
| U
| L

string-literal
| encoding-prefixopt" s-char-sequenceopt"
| encoding-prefixopt[R raw-string
encoding-prefix
| u8
| u
| U
| L

and marks a wide string literal:

并标记一个宽字符串文字:

11) A string literal that begins with L, such as L"asdf", is a wide string literal. A wide string literal has type “array of nconst wchar_t”, where n is the size of the string as defined below; it has static storage duration and is initialized with the given characters.

11) 以 开头的字符串文字L,例如L"asdf",是宽字符串文字。宽字符串文字的类型为“array of nconst wchar_t”,其中 n 是字符串的大小,定义如下;它具有静态存储持续时间并使用给定的字符进行初始化。

回答by David

The meaning of L here is wide character: wchar_t. String with L is coded in 16bit rather than 8bit, take an example:

L在这里的意思是宽字符:wchar_t。带L的字符串用16bit而不是8bit编码,举个例子:

"A"    = 41
L"A"   = 00 41