5

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.

1
  • 1
    You're getting a compiler error, not an exception in the first case. Commented Dec 18, 2015 at 17:55

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Won by 30 seconds... you're fast. +1
ok then, the compiler complains when evaluates both numbers but it doesn't when evaluates the number and the variable "ten". You are forced to use checked in order to recognize overflow on that case. It's a bit of incoherence, isn't it?
If you want the same behavior (at runtime) just check the box in the project settings to make it "checked" by default instead "unchecked", or wrap the code in a checked block 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.
It does not force the same behavior, Compiler will not give a compile error for checked version of int b = 2147483647 + ten; either. @ScottChamberlain
@ScottChamberlain I see, Advanced settings: "Check for arithmetic overflow/underfow" TA

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.