简体   繁体   中英

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 .

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?)

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.

Quote from N1256 6.5 Expressions:

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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