Why does the compiler match “char” to “int” but not “short”?

前端 未结 2 561
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 19:38

I\'ve got a small program:

#include
using namespace std;

void f(int)   { cout << \"int\\n\";   }
void f(short) { cout << \"short\\n\         


        
2条回答
  •  野的像风
    2021-01-30 20:22

    From Implicit conversion (cppreference):

    The following implicit conversions are classified as integral promotions:

    • [...]
    • char can be converted to int or unsigned int depending on the underlying type: signed char or unsigned char (see above);
    • [...]

    So, if there is a function f(int) and f(short), the compiler will try to do an integer promotion first, if it is not possible, it will fallback to a integer conversion.

    char to int is an integer promotion (see above), so the compiler will choose it.

    If there isn't any f(int), the compiler will fail to find a function where it can do integer promotion, and will fallback to integer conversion. It finds a f(short), and a char can be converted into a short, so it will choose it.

提交回复
热议问题