main() {
if ( -1 < (unsigned char) 1 )
printf("less than");
else
printf("NOT less than");
}
打印小于
。因为,(unsigned char) 1
被转换为 (signed char) 1
,然后: (signed) -1 (有符号)1
,因此输出小于
。
但是,如果我将上面的代码更改为 if ( (-1 < (unsigned int) 1 )
,
则输出不小于
。
因此,很明显,当我将 unsigned char 更改为 unsigned int 时:
- (signed) -1 转换为 unsigned int [发生的情况正好相反],
- 因为 -1 存储为 2 的补码 1;位模式被评估为 255(可能) )
- 因此 255 < 1 将计算为 false,
- 即使您用
int a = -1;
代替 '-1' 也会执行相同的结果
问题:
-
在有符号和无符号期间。算术...如何确定有符号是否会转换为无符号,反之亦然。
- 。 unsigned char 和 char 之间的算术转换是否不同:显然 unsigned 转换为有符号,unsigned int 和 int :显然有符号转换为无符号
PS:我知道这不依赖于编译器..所以不要说它是。
main() {
if ( -1 < (unsigned char) 1 )
printf("less than");
else
printf("NOT less than");
}
Prints less than
. Because, (unsigned char) 1
is converted to (signed char) 1
and then: (signed) -1 < (signed) 1
, thus output is less than
.
But if I change the above code to if ( (-1 < (unsigned int) 1 )
then the output is NOT less than
.
So it's obvious that when I change unsigned char to unsigned int:
- (signed) -1 is converted to unsigned int [exactly opposite is happening]
- since -1 is stored as 2's compliment of 1; the bit-pattern is evaluated as 255 (probably)
- thus 255 < 1 will evaluate to false and else will execute.
- even if you substitute
int a = -1;
in place of '-1' same result
Questions:
-
during signed and unsigned arithmetic...how to be sure if signed will be converted to unsigned or vice versa.
-
why is conversion different for arithmetic between unsigned char and char : apparently unsigned is converted to signed and unsigned int and int : apparently signed is converter to unsigned
PS: I know this is not compiler dependent..so don't say it is.
发布评论
评论(2)
规则如下:
规则如下:
-1
-1
-1
-1
-1
-1
-1
(unsigned char) 1
首先,两个操作数都转换为 int(因为 int 可以表示 unsigned char 的所有值)。然后对这些有符号类型进行比较。然后使用规则 1。比较成功。
int 不能表示 unsigned int 的所有值,因此使用规则 3,并将有符号整数转换为无符号整数 (UINT_MAX - 1)。现在比较失败了。
The rules are as follows:
The rules then work as follows:
-1 < (unsigned char) 1
First both operands are converted to ints (because an int can represent all values of unsigned char). Then the comparison is made on these signed types. Rule 1 is then used. The comparison succeeds.
-1 < (unsigned int) 1
An int cannot represent all the values of an unsigned int so rule 3 is used and the signed integer is converted to an unsigned integer (UINT_MAX - 1). The comparison now fails.
这是由于整数促销。两个参数都可以表示为 int,因此它们都会转换为 int。
ISO C 6.3.1.1,第 2 段:
This is due to integer promotions. Both arguments can be represented as an int, so they are converted to an int.
ISO C 6.3.1.1, paragraph 2: