Type in C

I am completely confused by the following code:

#include <stdio.h> #include <stdint.h> int main(int argc, char ** argv) { uint16_t a = 413; uint16_t b = 64948; fprintf(stdout, "%u\n", (a - b)); fprintf(stdout, "%u\n", ((uint16_t) (a - b))); return 0; } 

This returns:

 $ gcc -Wall test.c -o test $ ./test 4294902761 1001 $ 

The expression (a - b) seems to be of type uint32_t. I do not understand why, since both operators are: uint16_t.

Can someone explain this to me?

+6
source share
3 answers

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

If both operands are of arithmetic type, ordinary arithmetic conversions are performed .

(Β§6.3.1.8 Ordinary arithmetic conversions):

... in both operands, whole promotions are performed.

(Β§6.3.1.1 Boolean, symbols and integers):

If int can represent all values ​​of the original type, the value is converted to an int value; ... They are called whole shares. All other types are not affected by whole promotions.

Since int can represent all uint16_t values ​​on your platform, a and b converted to int before subtraction. The result is of type int and passed to printf as int . You specified the %u formatter with an int argument; strictly speaking, this causes undefined behavior, but on your platform, the int argument is interpreted as its two-component representation, and it prints.

+14
source

If you throw away the upper bits of a number (by explicitly casting to an unsigned 16-bit integer), you will get a smaller result (in the range 0 and 2 ^ 16-1) than before.

+1
source

C pushes the arguments to unsigned int before doing the subtraction. This is standard behavior.

See, for example, In a C expression in which there are unsigned int and signed int, what type will be raised to what type? for details.

0
source

Source: https://habr.com/ru/post/900439/


All Articles