开发者

Not sure what this code is doing

What is the difference between the two results here? I have seen things like this but don't understand at all. Imagine the following program:

int main() {

vector<int> v(4);
for (int i = 0; i < 4; i++) v[i] = i; 

cout << v[3] <&l开发者_JAVA百科t; endl;
cout << v[3] - '0';

return 0;
}

v[3] will return 3 and v[3]-'0' will return -45

I am just curious about this.


Answers are correct, except nobody mentioned the reason, C++ integer promotions require that char type is promoted to int in v[3] - '0' expression, had the types be different (e.g. vector<char> v(4)), the answer would be quite different as well.


'0' is the character zero, which has ASCII code 48. Hence, v[3] - '0' is actually v[3] - 48.


If you look at ASCII table '0' is equal to decimal 48. 3-48=-45

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜