Assign 2 char to an int

2019-05-16 12:00发布

问题:

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';



标签: c++ char int ascii