简体   繁体   English

在c中的if语句中对表达式的求值

[英]evaluation of an expression in an if statement in c

suppose i write a code as: 假设我将代码写为:

int main()
{
    int i,a=2147483647;

    if((2*a)<0)
        printf("hello");
    else
    printf("world");
}

the output is world. 输出就是世界。 but for : 但对于 :

int main()
{
    int i,a=2147483647;
    if((a+a)<0)
        printf("hello");
    else
        printf("world");
}

The output is hello . 输出是hello

How is this happening? 这是怎么回事?
And where is the value of 2*a and a+a stored in memory(what is the datatype of the memory location?) 内存中存储的2 * a和a + a的值在哪里(存储位置的数据类型是什么?)

If your INT_MAX is 2147483647 ( pow(2, 31) - 1 ), 2*a and a+a do cause overflow, and overflow in signed integer aritimetic is undefined behavior in C. 如果您的INT_MAX2147483647pow(2, 31) - 1 INT_MAX pow(2, 31) - 1 ),则2*aa+a确实会导致溢出,并且有符号整数算术溢出是C中的未定义行为

Quote from N1256 6.5 Expressions: 引用N1256 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. 5如果在表达式的求值过程中发生异常情况 (即,如果未在数学上定义结果或该结果不在其类型的可表示值范围内),则该行为不确定。

Undefined behavior can cause everything . 未定义的行为会导致一切 See your compiler's output to know the reason for this specific result. 查看编译器的输出以了解产生此特定结果的原因。

To know where the value of 2*a and a+a are stored, also see your compiler's output. 要知道2*aa+a的值存储在哪里,还请参见编译器的输出。 I guess they should be stored in register, not in memory if your compiler is smart enough. 我想如果您的编译器足够聪明,它们应该存储在寄存器中,而不是内存中。 Some poor compiler may store their value on the stack on the memory. 一些性能差的编译器可能会将其值存储在内存中的堆栈中。

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

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