作者loveme00835 (朴髮箍)
看板C_and_CPP
標題Re: [問題] 新手關於字元的問題
時間Fri Apr 22 21:41:28 2011
※ 引述《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
→ james732:其實我想問板主,為什麼會想去閱讀規格書呢? 04/22 21:42
→ james732:那樣的東西我實在沒有耐心看...XD 04/22 21:43
推 purpose:板主是有開過真理之門嗎 04/22 21:46
之前看到 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;
看了會比較知道為什麼某些地方要設計成那樣, 不需去死背, 看懂
也會有成就感!
推 tomap41017:那個 lambda...也太XD 04/22 23:19
※ 編輯: loveme00835 來自: 140.121.197.115 (04/23 00:18)