Unicode 转义序列与十六进制值

Unicode escape sequences vs hexadecimal values

为了在我的程序中编码 Unicode/UTF-8 个字符,我一直在使用 \uXXXX 转义序列,例如:

wchar_t superscript_4 = L'\u2074';  // U+2074 SUPERSCRIPT 4 '⁴'
wchar_t subscript_4   = L'\u2084';  // U+2084 SUBSCRIPT 4 '₄'

但是,使用十六进制应该没问题,因为 Unicode 是以十六进制编码的。

wchar_t superscript_4 = 0x2074;
wchar_t subscript_4   = 0x2084;

第二个例子能正确编码字符吗?我会 运行 遇到宽字符问题、分段错误或错误存储的字符值吗?如果是这样,为什么?如果不是,为什么?

可以用十六进制常量初始化它们,但你也可以用数字常量初始化正常的chars,例如char c = 67;。它的工作方式相同;它分配 charwchar_t 具有 int 的值。在您给出的示例中,假设一个 Unicode 执行环境(不能完全保证但很有可能)它是下标或上标 4;在我的示例中,它是大写 C.

In particular, for regular chars, technically character constants like 'C' have type int, and you are usually assigning int values to chars. For wchar_ts, the constants do actually have wchar_t type, and the integral value is the same value you’d get by calling mbtowc。所以假设你在 Unicode 环境中工作,十六进制常量等同于 Unicode 转义。

不过,通常你不想这样做;使用字符文字可以更清楚地说明您的意图。如果您在源代码中使用非 ASCII 字符,则尤其如此,在这种情况下,您可以将代码设为

wchar_t superscript_4 = L'⁴'
wchar_t subscript_4   = L'₄'

另请注意,对于许多用途,最好使用 char16_tchar32_t,因为 wchar_t 在不同平台上可能有不同的宽度;在您有特定需要切换到其他东西之前,只使用 UTF-8 可能也更干净。