My computer thinks Signed Int is less than -1?

See the answer in English> Why is (sizeof(int)> -1) false?





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

The result is 0(FALSE).
How could this happen?
I am using 64-bit ubuntu linux, the result should be (4> -1)=> 1 => true.

The type of sizeof(signed int) is size_t, which is an unsigned type. When you compare between a signed value and an unsigned value [and the type of an unsigned value is at least The type of the signed value is the same), the signed value is converted to an unsigned value before the comparison. This conversion makes -1 the maximum possible value of the unsigned type. In other words, it is as if you wrote

< /p>

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

When you make this mistake, you can make gcc warn, but by default it is not even turned on-you need -Wextra or more specifically -Wsign-compare. (This warning can cause a lot of errors Report, but I think it is very useful to open the new code.)

See the English answer> Why is (sizeof(int)> -1) false? 3
> Comparison operation on unsigned and signed integers 7

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

The result is 0(FALSE).
How could this be?
I am using 64-bit ubuntu linux, the result should be (4> -1)=> 1 => true.

sizeof(signed int ) Is of type size_t, which is an unsigned type. When you compare between signed and unsigned values ​​[and the type of the unsigned value is at least as large as the type of the signed value], before the comparison Convert a signed value to an unsigned value. This conversion makes -1 the largest possible value of an unsigned type. In other words, it’s just like you wrote

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

When you commit this You can make gcc warn when there is an error, but it is not even turned on by default-you need -Wextra or more specifically -Wsign-compare. (This warning will generate a lot of false positives, but I think it’s useful to open new code.)

Leave a Comment

Your email address will not be published.