简体   繁体   English

为什么下面的代码不打印测试?

[英]why the code below is not printing TEST?

Why the code below doesn't show an output. 为什么下面的代码没有显示输出。 It shoudl do arithmetic converion by why not: 它应该通过为什么不进行算术收敛:

#include <stdio.h>

int main(void)
{
    int b=2147483647;
    if((b+1)==2147483648u)
    {
        printf("TEST\n");
    }
    return 0;
}

Here is 这是

printf("%d\n",b+1); // shows -2147483648

printf("%u\n",(unsigned int)b+1); // shows 2147483648

The expression b+1 is an overflow, because 2147483647 is the maximum value of a signed int (assuming 32-bit ints). 表达式b+1是一个溢出,因为2147483647是一个有符号的int的最大值(假定为32位int)。 Overflowing a signed expression is undefined behavior, so you can't reason about anything that happens after that. 溢出带符号的表达式是未定义的行为,因此您无法推断之后发生的任何事情。

If you cast b to unsigned int before incrementing it, it should work correctly. 如果在递增b之前将其bunsigned int ,则它将正常工作。

Reference: C11 6.5/5: 参考:C11 6.5 / 5:

If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined. 如果在表达式的求值过程中出现异常情况(即,如果结果没有在数学上定义或不在其类型的可表示值范围内),则行为不确定。

2147483647 is the largest number that can be stored in an int data-type variable, as a signed integer variable has 32 bits lf memory allocated to it. 2147483647是可以存储在int数据类型变量中的最大数字,因为带符号的整数变量具有分配给它的32位lf内存。 The last bit, the 32nd bit, is allocated for the sign of the number. 最后一位,第32位,分配给数字的符号。 Therefore, that means you only have 31 bits of memory assigned for the number itself, making the largest number 2^31, which is 2147483647. 因此,这意味着您只为数字本身分配了31位内存,从而使最大数字2 ^ 31,即2147483647。

Doing 2147483648, which is greater than 2147483647, is referred to as integer overflow, which will result to undefined behaviour. 大于2147483647的操作2147483648被称为整数溢出,这将导致不确定的行为。

When you do 2147483648u, you store the number as an unsigned number, hence deallocating ghe 32nd bit originally meant for the sign, to store a number instead. 当您执行2147483648u时,您将数字存储为无符号数字,因此取消分配最初用于该符号的第32位来存储数字。 This means that you can now store the largest number: 2^32, which equals 4294967296. That is the reason why you can now store 2147483648 without invoking integer overflow, and causing undefined behaviour. 这意味着您现在可以存储最大数目:2 ^ 32,等于4294967296。这就是为什么现在可以存储2147483648而无需调用整数溢出和引起未定义行为的原因。

What you should do is: 您应该做的是:

  • cast your variable to unsigned int 将变量转换为unsigned int
  • add a "u" to the end of the number, like 2147483648u 在数字的末尾添加“ u”,例如2147483648u

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM