Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 859
Rober Avatar asked Dec 18 '15 17:12

Rober


People also ask

What is an integer overflow error?

An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).

What is a overflow exception?

An OverflowException is thrown at run time under the following conditions: An arithmetic operation produces a result that is outside the range of the data type returned by the operation.

How do I get rid of integer overflow in Java?

Use a Different Data Type. If we want to allow values larger than 2147483647 (or smaller than -2147483648), we can simply use the long data type or a BigInteger instead. Though variables of type long can also overflow, the minimum and maximum values are much larger and are probably sufficient in most situations.

How do you handle integer overflow?

In languages where integer overflow can occur, you can reduce its likelihood by using larger integer types, like Java's long or C's long long int. If you need to store something even bigger, there are libraries built to handle arbitrarily large numbers.


1 Answers

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.

like image 190
Hamid Pourjam Avatar answered Nov 01 '22 18:11

Hamid Pourjam