我的电脑认为有符号整数比-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 64bit ubuntu linux so the result should be (4 > -1) => 1 => True.
结果是0 (FALSE)。为什么会这样呢?我使用64位ubuntu linux,所以结果应该是(4 > -1)=> 1 =>为真。
3 个解决方案
#1
8
sizeof(signed int)
has type size_t
, which is an unsigned type. When you make a comparison between a signed and an unsigned value [and the unsigned value's type is at least as large as the signed value's type], the signed value is converted to unsigned before the comparison. This conversion causes -1
to become the largest possible value of the unsigned type. In other words, it is as if you wrote
sizeof(带符号int)具有类型size_t,这是一个无符号类型。当您在一个有符号的值和一个无符号的值之间进行比较时[且无符号的值的类型至少与有符号的值的类型一样大],在比较之前将有符号的值转换为无符号的值。这种转换使-1成为无符号类型的最大可能值。换句话说,就好像你写了一样
#include <limits.h>
/* ... */
printf("%d", sizeof(signed int) > SIZE_MAX);
You can make gcc warn when you make this mistake, but it's not on by default or even in -Wall
: you need -Wextra
or more specifically -Wsign-compare
. (This warning can produce a great many false positives, but I think it's useful to turn on for new code.)
当您犯这个错误时,您可以发出gcc警告,但它不是默认的,甚至不是在-Wall中:您需要-Wextra或更具体地-Wsign-compare。(这个警告可能会产生大量的误报,但我认为打开新代码是有用的。)
更多相关文章
- Linux下符号版本原理及实现
- 请问有谁知道linux上生成的共享库中,使用nm列出来的符号都可以在
- 来点基础的--诡异的极客们的符号--流、管道和文件的耦合
- 特殊符号对应的ASCII码
- SHOW STATUS 查看各种类型SQL执行的频率
- 类型不敏感的nvarchar类型的主键,其中ß!= ss
- SQL Server CLR函数类型不匹配。
- SQL Server 中 存储“经纬度”应设置的数据类型
- 每条sql语句实际上都是一个事物(事物多种类型解读)