Assign 2 char to an int

99封情书 提交于 2019-12-22 10:19:10

问题


I am trying to understand the outcome of this code:

#include<iostream>

using namespace std;

int main()
{
    int a = 'dd';
    cout << a;
    return 0;
}

The result is 25700. How the compiler get this number? Thanks


回答1:


The ascii code for 'd' is 0x64. The literal 'dd' was represented as 0x6464 by your compiler, which is 25700 when written in decimal notation.




回答2:


'dd' is a multi-character literal, its type is int and its value is implementation-defined.

In many implementations, the value is calculated as 256 * 'd' + 'd', which is 25700.


From C++11 §2.13.2 Character literals

... An ordinary character literal that contains more than one c-char is a multicharacter literal. A multicharacter literal has type int and implementation-defined value.




回答3:


'dd' was implicitly converted to int value by the statement int a='dd';



来源:https://stackoverflow.com/questions/29101247/assign-2-char-to-an-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!