When can I not declare an int with a signature?

In C, it is assumed that declared integers like -1 are declared with a keyword signed, for example:

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?

+3
source share
5 answers

Since you have confirmed that you are printing using:

printf("%d", i);

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:

If the conversion specification is not valid, the behavior is undefined. 248) [...]

, 3.4.3 undefined, :

,

:

undefined , , ( ), ( ).

, , int int. , 6.7.2 , 2 int :

int, int

5 :

, , [...]

+3

, , printf:

  • %d, .
  • %u, .
+3

printf , . C , , .

unsigned int printf %d, undefined. , -.

, , , , . .

+1
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
0

2 :

  • - 64 ( 32 ) .
  • Printf - , .

(-2) printf .

, "signed" unsigned , . printf , , . ( , . )

, .

( - , 2 . - , , , , , , , .

, "undefined". .

0

All Articles