In C, it is assumed that declared integers like -1 are declared with a keyword signed, for example:
signed
signed int i = -1;
However, I tried this:
signed int i = -2; unsigned int i = -2; int i = -2;
and all 3 cases print -2 with printf("%d", i);. Why?
printf("%d", i);
Since you have confirmed that you are printing using:
this is undefined behavior in an unsigned case. This is described in the C99 draft section of the 7.19.6.1fprintf function, which also covers printfformat specifiers, as stated in clause 9:
7.19.6.1
printf
If the conversion specification is not valid, the behavior is undefined. 248) [...]
, 3.4.3 undefined, :
3.4.3
,
:
undefined , , ( ), ( ).
, , int int. , 6.7.2 , 2 int :
6.7.2
int, int
5 :
, , [...]
, , printf:
%d
%u
printf , . C , , .
unsigned int printf %d, undefined. , -.
unsigned int
, , , , . .
unsigned int i = -2; // i actually holds 4294967294 printf("%d", i); // printf casts i back to an int which is -2 hence the same output
2 :
(-2) printf .
, "signed" unsigned , . printf , , . ( , . )
, .
( - , 2 . - , , , , , , , .
, "undefined". .