概述
\x轉義的定義是這樣的
轉義符 | 字符值 | 輸出結果 |
\xh[h...] | 具有此十六進制碼的字符 | 輸出此字符 |
問題
看似\x后面可以接受1或n個十六進制的字符,但是如果你把一個超過ff分十六進制數賦值給一個char變量,會得到一個"Out of range"的提示;
#include <stdio.h> #include <wchar.h> int main(void) { char a = '\x123'; printf("%d\n", a); }
c28.c: In function ¡®main¡¯: c28.c:10:11: warning: hex escape sequence out of range [enabled by default] char a = '\x123';
分析
這是因為char類型只能容納1byte的數,面對十六進制123是無能為力的,但是,即使是把char類型換成wchar_t類型,貌似也會有問題;
#include <stdio.h> #include <wchar.h> int main(void) { wchar_t a = '\x123'; printf("%d\n", a); }
c28.c: In function ¡®main¡¯: c28.c:10:14: warning: hex escape sequence out of range [enabled by default] wchar_t a = '\x123';
但如果用L預處理符號以表明一下這個/段字符是寬字符,就不會出現問題。這是因為聲明字符變量時如果不表明該字面量是寬字符,編譯器默認會當成窄字符去處理,而一個窄字符的大小只有1byte
#include <stdio.h> #include <wchar.h> int main(void) { wchar_t a = L'\x123'; printf("%d\n", a); }
291
當然,寬字符(也就是wchar_t類型)也有大小限制,這通常視系統而定,一般系統一個寬字符的大小是4byte。如果你輸入的十六進制值大於4byte,那么編譯器也會報"Out of range";
另外,\x跟字符位數無關,也就是說\x61、\x061和\x000000061三者是一個意思
#include <stdio.h> #include <wchar.h> int main(void) { char a = '\x0000000061'; printf("%d\n", a); }
97
總結
\x確實可以接受1或n個十六進制數,只是要看賦值變量類型是否匹配
題外話
其他語言跟C會有一點差異,例如在javascript和PHP,\x只會接受前兩位十六進制數,后面(要是有)則當普通字符處理。