Having the following code:
0 #include<stdio.h>
1
2 int
3 main(void)
4 {
5 int x;
6 x = -3;
7
8 for (int i = 0; i < 5; i++)
9 {
10 printf("%d\n", (unsigned int) (x - i)); //necessita mesmo de parêntesis aq?
11 printf("%u\n", (int) (x - i)); //necessita mesmo de parêntesis aqui?
12
13 printf("%d\n", x - i);
14 printf("%u\n\n", x - i);
15 }
16
17 return 0;
18 }
To compile I used: gcc -Wall -pedantic -std=c99 -o test.exe test.c
The output of the code above was as follows:
-3
4294967293
-3
4294967293
-4
4294967292
-4
4294967292
-5
4294967291
-5
4294967291
-6
4294967290
-6
4294967290
-7
4294967289
-7
4294967289
Doubt 1) On lines 10 and 11 the compiler temporarily converts the types to the given casting type and then converts implicitly to %d
and %u
types or simply ignores casting and formats directly according to the specifier formatting?
Doubt 2) The unsigned int
converts a signed int
to an unsigned int
. But anyway, how does the compiler do this? Note that the above code outputs when printing a negative integer by formatting it to unsigned int
(in the case of code above, implicitly in lines 11 and 14) the output is an integer value (different from the desired one) that decreases proportionally to the value wanted. Why does this occur?