-1); return 0; } ...">

Does my computer think the signed int is less than -1?

#include <stdio.h>
int main(void)
{
    printf("%d", sizeof(signed int) > -1);
    return 0;
}

the result is 0 (FALSE). how can it be? Im using 64-bit ubuntu linux, so the result should be (4> -1) => 1 => True.

+3
source share
3 answers

sizeof(signed int)has a type size_tthat is an unsigned type. When you make a comparison between a signed and unsigned value [and the unsigned value type is at least as large as the signed value type), the sign value is converted to unsigned before the comparison. This conversion leads to what -1becomes the largest possible value of an unsigned type. In other words, it is as if you wrote

#include <limits.h>
/* ... */
printf("%d", sizeof(signed int) > SIZE_MAX);

gcc-, , -Wall: -Wextra , , -Wsign-compare. ( , , .)

+8

- sizeof (size_t). , -1 unsigned, .

:

printf("%d", ((int)sizeof(signed int)) > -1);
+10

C , , " ", . 1

, , , , . . , , , . , size_t , int.

, -1 , , unsigned.


1. ISO/IEC 9899: 1999 ( "C99" ) 6.3

+5

All Articles