Search code examples
c++c++11type-deduction

Why is the type here deduced to be uint32_t?


The following code is deducing the auto to uint32_t. I am trying to understand why it is so.

auto value = a + b * c;

where a is int32_t, b is uint32_t and c is int.


Solution

  • Type conversion rules are a bit weird sometimes. Every type is given a rank, but every platform can implement the conversions as it fits them, with generally only few rules.

    securecoding has a nice wrap up:

    Integer Conversion Rank

    Every integer type has an integer conversion rank that determines how conversions are performed. The ranking is based on the concept that each integer type contains at least as many bits as the types ranked below it. The following rules for determining integer conversion rank are defined in the C Standard, subclause 6.3.1.1 [ISO/IEC 9899:2011]:

    • No two signed integer types shall have the same rank, even if they have the same representation.

    • The rank of a signed integer type shall be greater than the rank of any signed integer type with less precision.

    • The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int, which shall be greater than the rank of signed char.

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

    • The rank of any standard integer type shall be greater than the rank of any extended integer type with the same width.

    • The rank of char shall equal the rank of signed char and unsigned char.

    • The rank of _Bool shall be less than the rank of all other standard integer types.

    • The rank of any enumerated type shall equal the rank of the compatible integer type.

    • The rank of any extended signed integer type relative to another extended signed integer type with the same precision is implementation-defined but still subject to the other rules for determining the integer conversion rank.

    • For all integer types T1, T2, and T3, if T1 has greater rank than T2 and T2 has greater rank than T3, then T1 has greater rank than T3.

    The integer conversion rank is used in the usual arithmetic conversions to determine what conversions need to take place to support an operation on mixed integer types.