Search code examples
cinteger-promotionstdintconversion-rank

How does type conversion and integer promotion work for stdint.h?


In C, I understand type conversions, integer promotion, casting, etc. for standard types, but how do the stdint.h types factor into this?

For type rankings, the rules state:

  • No two signed integer types shall have the same rank, even if they have the same representation.
  • The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type, if any.

So assuming an int is 32 bits, does this mean int > int32_t = uint32_t > short int in the rankings?

Also, are the stdint.h types also subject to integer promotion? For example if I try to add a signed char to a uint32_t, they will both get promoted to unsigned ints?


Solution

  • To answer your first question: no. Since int32_t is usually defined with a typedef like this

    typedef int int32_t;
    

    it is the same as int and will have the same rank as int.

    To answer the second question: yes. Integer promotion still applies. The types defined in stdint.h behave just like the types they are aliases of.

    By the way, to be more confident in how your compiler behaves, you can test all of these things in your compiler by writing invalid code like this and carefully looking at the error message, which will (if you have a good compiler) reveal the type of the expression on the right hand side:

    void * x = (signed char)-1 + (uint32_t)0;