Re: [問題] 新手關於字元的問題
※ 引述《Dirichlet (微風輕吹)》之銘言:
: 請問為啥
: #include<iostream>
: using namespace std;
: int main()
: {
: cout<<'10'<<endl;
: }
: 執行後會出現 12592 呢?
: 而 '10' 中的 10 如果改成 0~9 就是 0~9,@@?
(只是)編譯會過, 這時要注意的是: 「'10' 的型態為何?」, 可以
使用下面程式碼來確定:
assert( typeid('10') == typeid(int) );
// [Warning] multi-character character constant
它是被當成整數來印...而且其實它也不是一個合法的寬/窄字元內
容:
wchar_t wc = L'10';
// [Warning] character constant too long for its type
char c = L'10';
// [Warning] character constant too long for its type
另外 C99 6.4.4.4/10 中有提到:
An integer character constant has type int. [...] The value
of an integer character constant containing more than one
character (e.g. 'ab'), or containing a character or escape
sequence that does not map to a single-byte execution
character, is implementation-defined. [...]
(110423 補充)
C++ 2.13.2/1
[...] An ordinary character literal that contains more
than one c-char is a multicharacter literal. A multichara-
cter literal has type int and implementation-defined value.
所以標準並沒有保證你「包好幾個字元」這件事在不同情境下都有
絕對相同的行為!唯一例外是這些字元s是用來表達字元變數的內存
值, 而非顯示的內容:
cout << '\x41' << endl; // 0x41 == 65 == 'A'
順帶一提, 要記住下面程式碼:
assert( (warning == bug) &&
(undefined behavior == bug) );
--
▂▅▂ ▁ ● ◣ 朴 ☆ 素 ★ 妍 ◢
◢ ◣ ◢▂▂◣ ◢▂※◣ ◢▄▂◣ T.T.L Listen 2
★ ★ ★ ★ ▉ ★ ★▏▉ ★ ★◣ http://ppt.cc/jIUk
◥ˇ◢ ▃◥ˇ◤▃ ◥ˇ◤ ◥ˇ◤◢ 說什麼結束
▃▃▇▃▃ ◢▇◣ ▋▎ ▋¥▎ ◢ http://ppt.cc/zQtB
▼ ▼ ▼ ▼ ψ髮箍 ◤ ◣
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.121.197.115
→
04/22 21:42, , 1F
04/22 21:42, 1F
→
04/22 21:43, , 2F
04/22 21:43, 2F
推
04/22 21:46, , 3F
04/22 21:46, 3F
之前看到 loveflames大PO一些規格書內文, 覺得很有趣我就 K 下
去了, 就無聊當小說來讀囉~ 之前一陣子被 n3291 的 lambda
expression 其中一段搞死:
int a = 1, b = 1, c = 1;
auto m1 = [a, &b, &c]() mutable {
auto m2 = [a, b, &c]() mutable {
std::cout << a << b << c;
a = 4; b = 4; c = 4;
};
a = 3; b = 3; c = 3;
m2();
};
a = 2; b = 2; c = 2;
m1();
std::cout << a << b << c;
看了會比較知道為什麼某些地方要設計成那樣, 不需去死背, 看懂
也會有成就感!
推
04/22 23:19, , 4F
04/22 23:19, 4F
※ 編輯: loveme00835 來自: 140.121.197.115 (04/23 00:18)
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章