简体   繁体   中英

Narrowing conversion from int to unsigned char

When I try to compile this code

struct T
{
    unsigned char x;
};

int main()
{
    unsigned char a = 10;
    unsigned char b = 1;

    T t = {a + b};

    return 0;
}

I get this error:

error: narrowing conversion of '(((int)a) + ((int)b))' from 'int' to 'unsigned char' inside { } [-Wnarrowing]|

Can anyone explain me why?

The operands to your addition expression are undergoing integral promotion .

In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable. This conversion always preserves the value.

Your a and b are being promoted to int or unsigned int , added, and then converted back down to unsigned char .

If the conversion is expected program behavior (from your point of view as the designer), you can explicitly cast it to the type you want. An explicit cast is not a narrowing conversion. An implicit cast is. So if we change the implicit cast to an explicit cast, the program is no longer ill-formed.

T t = { static_cast<unsigned char>(a + b) };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM