为什么这两个C语句都产生相同的输出 [英] Why do both of these C statements produce same outputs

查看:68
本文介绍了为什么这两个C语句都产生相同的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
int main() {
     int x = 0x80000000;
     printf("%i\n",(((x - 1) >> 31) & 1));  //shows 0 as output
     printf("%i\n",!(((x - 1) >> 31) & 1));  //shows 0 as output(expected 1)
}

为什么会这样?由于两个语句都执行相同的操作,除了!操作员.为什么第二个printf没有给出1作为输出?据我所知,逻辑不超过0给出1,逻辑不超过其他数给出0.我在这里做错了吗?

Why is this happening? As both the statements perform the same operation except the ! operator. Why do the second printf not give 1 as output? From what I know a logical not over 0 gives 1 and logical not over other numbers gives 0. Am I doing something wrong here?

推荐答案

您在这里看到的是假定使用二进制补码的32字节 int ,则值0x80000000不在 int 的范围内,因此将进行实现定义的转换.很有可能,它转换为值-2147483648,这是系统上 int 中可以保存的最小值.

Assuming a 32-byte int using two's complement, the value 0x80000000 is outside the range of int, so it undergoes an implementation-defined conversion. Most likely, it converts to the value -2147483648 which is the minimum value that can be held in a int on your system.

在两种情况下,您要做的下一步都是从该值中减去1.这不是保证可以解决的问题.这被认为是溢出,是未定义的行为.这就是为什么您看到自己看到的结果的原因.一旦您具有未定义的行为,就无法保证该程序将执行的操作.

The next thing you do in both cases is subtract 1 from this value. This is not guaranteed to wrap around. This is considered overflow and is undefined behavior. This is why you see the results you're seeing. Once you have undefined behavior, there are no guarantees what the program will do.

这篇关于为什么这两个C语句都产生相同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆