1

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

Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
  • 5
    Overflow in signed integer aritimetic is *undefined behavior*. – MikeCAT Dec 13 '15 at 08:38
  • 2
    The value of `2*a` and `a+a` may be stored in an register and nowhere in memory. See your compiler's output for further investigation. – MikeCAT Dec 13 '15 at 08:39
  • 1
    To see the value of `a+a` put it in another *int* – Déjà vu Dec 13 '15 at 08:43
  • 1
    It may depend on your machine, OS and compiler. Ubunto 4.8.2 with gcc 4.8.4 gives `hello` on both – LeeNeverGup Dec 13 '15 at 08:45
  • 1
    This can be compiler dependent. Study the assembly language generated in the case of no specific assignment (like you are doing in the conditional expression) and compare that to the explicit assignment to an int, unsigned int, long, unsigned long, etc. Its best though to always assign to a data type to avoid problems like this. Makes it easier to debug too. – Kerry Kobashi Dec 13 '15 at 08:52
  • Can you post the assembly of both implementations of main? Most debuggers have a way to get at it. – selbie Dec 13 '15 at 08:56

1 Answers1

6

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.

alk
  • 69,737
  • 10
  • 105
  • 255
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Is overflow undefined with *unsigned* integers? Or does it have predictable behavior? – selbie Dec 13 '15 at 08:49
  • @selbie It is defined. See N1256 6.2.5 Types or [c++ - Why is unsigned integer overflow defined behavior but signed integer overflow isn't? - Stack Overflow](http://stackoverflow.com/questions/18195715/why-is-unsigned-integer-overflow-defined-behavior-but-signed-integer-overflow-is) – MikeCAT Dec 13 '15 at 08:51
  • A good compiler would store it nowhere, excising the whole program since it causes UB :D – M.M Dec 13 '15 at 09:30