Rober
Rober

Reputation: 726

Integer overflow exception

Why I get a compiler error here:

int a = 2147483647 + 10;

and not here, if I'm performing the same operation:

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

I'm learning the usage of checked and the MSDN web site doesn't clear why the OverflowException is raised in the first code snippet:

By default, an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the range of the destination type. If the expression contains one or more non-constant values, the compiler does not detect the overflow.

It only explains the behavior but not the reasons for that behavior. I'd like to know what happens under the hood.

Upvotes: 5

Views: 1398

Answers (1)

Hamid Pourjam
Hamid Pourjam

Reputation: 20764

The reason is when you have int a = 2147483647 + 10; compiler can predict the result of statement(a) and it will know that it causes overflow because both 2147483647 and 10 are constants and their values are known at compile time.

But when you have

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

Some other thread (or something else, maybe a wizard, maybe a hazard in memory ...) may have change the value of ten before execution of int b = 2147483647 + ten; statement and the overflow can not be predicted at compile time.

Upvotes: 9

Related Questions