Why are the results of integer promotion different?

后端 未结 3 791
走了就别回头了
走了就别回头了 2020-12-10 12:30

Please look at my test code:

#include 
#include 


#define PRINT_COMPARE_RESULT(a, b) \\
    if (a > b) { \\
        printf         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 13:09

    The conversion process for C++ is described as the usual arithmetic conversions. However, I think the most relevant rule is at the sub-referenced section conv.prom: Integral promotions 4.6.1:

    A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank ([conv.rank]) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

    The funny thing there is the use of the word "can", which I think suggests that this promotion is performed at the discretion of the compiler.

    I also found this C-spec snippet that hints at the omission of promotion:

    11   EXAMPLE 2       In executing the fragment
                  char c1, c2;
                  /* ... */
                  c1 = c1 + c2;
         the ``integer promotions'' require that the abstract machine promote the value of each variable to int size
         and then add the two ints and truncate the sum. Provided the addition of two chars can be done without
         overflow, or with overflow wrapping silently to produce the correct result, the actual execution need only
         produce the same result, possibly omitting the promotions.
    

    There is also the definition of "rank" to be considered. The list of rules is pretty long, but as it applies to this question "rank" is straightforward:

    The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type.

提交回复
热议问题