Ordering matters

suggest change

There is overflow in the following code

int x = int.MaxValue;
Console.WriteLine(x + x + 1L);  //prints -1

Whereas in the following code there is no overflow

int x = int.MaxValue;
Console.WriteLine(x + 1L + x);  //prints 4294967295

This is due to the left-to-right ordering of the operations. In the first code fragment x + x overflows and after that it becomes a long. On the other hand x + 1L becomes long and after that x is added to this value.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents