3
 const int cMax = int.MaxValue;
 int vMax = cMax;
 int int1;
 int int2;
 int1 = cMax + 10;//Checked amd throws error
 int2 = vMax+10;//Unchecked and Overflows at runTime

Here it is seen that operations involving constant is checked by default and whereas operation involving variable is unchecked and passes compilation.

Why is this difference in compilation behavior?

2 Answers 2

6

The behavior is different because cMax + 10 is a constant expression. According to the C# Language Reference,

A constant expression is an expression that can be fully evaluated at compile time. A constant can participate in a constant expression, as follows:

public const int c1 = 5;  
public const int c2 = c1 + 100;

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.

Therefore, the compiler must evaluate your expression at compile time. Since it is unable to produce a valid value as the result of the computation, it produces a compile-time error. Use checked keyword to enable overflow checking for integers.

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

3 Comments

Yeah, that's a better answer then mine. +1.
Is there a possibility to check for overflow at compile time for variables?
@SamuelAC I strongly doubt it - the cases when it is possible and helpful are relatively rare, so the "bang for the buck" for the compiler team is pretty low.
1

Why is this difference in compilation behavior?

Generally people don't expect the variable to overflow when they write code. It is best to tell them whenever the compiler can that this will cause an overflow. If the programmer really want the operation to overflow, they can shut the compiler up by adding unchecked(...).

If you use compile-time constants, the compiler can evaluate the values of those constants and tell you that this might cause an overflow. If you have variables, the compiler don't know what values the variables have, so it can't tell for sure whether an operation will overflow.

Comments

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.