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.
-
1You're getting a compiler error, not an exception in the first case.CodesInChaos– CodesInChaos2015年12月18日 17:55:18 +00:00Commented Dec 18, 2015 at 17:55
1 Answer 1
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.
5 Comments
checked { int ten = 10; int b = 2147483647 + ten; }, that too will throw the same error at runtime. You can't get the behavior at compile time.int b = 2147483647 + ten; either. @ScottChamberlain