1
Having the code to follow:
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 above code 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 converts the types temporarily to the type determined in casting and later converts implicitly to the types %d
and %u
or simply skip casting and format directly according to format specifier ?
Doubt 2) The unsigned int
converts a int
with signal for a int
no sign. But after all, how does the compiler do it ? I noticed that the above code outputs when printed a negative integer formatting it to unsigned int
(in the case of the above code, implicitly, in rows 11 and 14) the output is an integer value (different from the desired) that decreases proportionally to the desired value. Because this occurs ?
But it is very common to use cast this way. I see even in books. Printf’s who said they were wrong give Undefined Behavior due to C90/C99 standards ? Or is it implemented-defined and GCC that generates Undefined Behavior ?
– ViniciusArruda
In the forefront,
(x - i)
is a type valueint
, the"%d"
requires aint
so the cast is wrong. In the second and fourth line the"%u"
requires aunsigned
so the cast is needed (in the second line the cast is completely unnecessary by converting a type into itself).– pmg