#1,072 – How the Unary Minus Operator Can Fail

There are cases when applying a unary operator to an operand results in a value that does not fit into the data type of the operand. Consider the int type, whose range is -2,147,483,648 to 2,147,483,647.  If we assign the minimum value (largest negative number) and try to negate it with the unary operator, the negation will fail.

By default, arithmetic operations work in an unchecked context.  In this case, the unary operator does nothing, just returning the value of the original operand.

            // int range is -2,147,483,648 to 2,147,483,647
            int n = int.MinValue;
            n = -n;  // n unchanged

If we do the same operation in a checked context, we’ll get an overflow exception.

1072-001

 

Note that a cast to a “larger” data type fails if it’s done outside of the unary operator.  But casting before applying the operator does work.

            long l = (long)-n;  // Still fails

            long l2 = -(long)n;  // This works

 

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: