type promotion in C

后端 未结 3 603
攒了一身酷
攒了一身酷 2021-01-05 08:33

I am quite confused by the following code:

#include 
#include 

int main(int argc, char ** argv)
{
    uint16_t a = 413;
    u         


        
3条回答
  •  长情又很酷
    2021-01-05 09:12

    The C standard explains this quite clearly (§6.5.6 Additive Operators):

    If both operands have arithmetic type, the usual arithmetic conversions are performed on them.

    (§6.3.1.8 Usual Arithmetic Conversions):

    ... the integer promotions are performed on both operands.

    (§6.3.1.1 Boolean, characters, and integers):

    If an int can represent all values of the original type, the value is converted to an int; ... These are called the integer promotions. All other types are unchanged by the integer promotions.

    Since int can represent all values of uint16_t on your platform, a and b are converted to int before the subtraction is performed. The result has type int, and is passed to printf as an int. You have specified the %u formatter with an int argument; strictly speaking this invokes undefined behavior, but on your platform the int argument is interpreted as it's twos-complement representation, and that is printed.

提交回复
热议问题