Integer overflow exception

Why am I getting a compiler error here:

int a = 2147483647 + 10; 

and not here if I perform the same operation:

 int ten = 10; int b = 2147483647 + ten; 

I am studying using checked , and the MSDN website does not understand why an OverflowException is thrown in the first code snippet:

By default, an expression containing only constant values โ€‹โ€‹causes a compiler error if the expression expresses a value that is outside the range of the destination type. If the expression contains one or more inconsistent values, the compiler does not detect overflow.

This explains the behavior, but not the reason for this behavior. I would like to know what is happening under the hood.

+5
source share
1 answer

The reason is that the compiler int a = 2147483647 + 10; can predict the result of operator ( a ), and he will know that it causes an overflow, since 2147483647 and 10 > are constants, and their values โ€‹โ€‹are known at compile time.

But when you

 int ten = 10; int b = 2147483647 + ten; 

Some other threads (or something else, perhaps a master, perhaps a danger in memory ...) may have changed the value of ten before executing the operator int b = 2147483647 + ten; , and overflow cannot be predicted at compile time.

+9
source

Source: https://habr.com/ru/post/1238658/


All Articles