Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing an integer value beyond its integer limit - C#

I've a for loop which keeps incrementing an integer value till the loop completes. So if the limit n is a double variable and the incremented variable 'i' is an integer, i gets incremented beyond its limits.

 double total = 0;
 double number = hugetValue;
 for (int i = 1; i <= number; i++)
 {
    total = total + i;
 }
 return total;

What happens to 'i' if it exceeds its capacity? How the value of i changes? Will i get a runtime error?

like image 280
NLV Avatar asked Jun 24 '10 07:06

NLV


People also ask

What happens when you increment an integer beyond its max value?

(Arithmetic) Integer Overflows 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 happens if you go over the integer limit?

An integer overflow can cause the value to wrap and become negative, which violates the program's assumption and may lead to unexpected behavior (for example, 8-bit integer addition of 127 + 1 results in −128, a two's complement of 128).

What happens if a stack exceeds its data limit?

In our computer's memory, stack size is limited. If a program uses more memory space than the stack size then stack overflow will occur and can result in a program crash.


2 Answers

Similar to the behaviour in some implentations of C where an int just wraps around from INT_MAX to INT_MIN ( though it's actually undefined behaviour according to the ISO standard), C# also wraps. Testing it in VS2008 with:

int x = 2147483647;
if (x+1 < x) {
    MessageBox.Show("It wrapped...");
}

will result in the message box appering.

If your hugetValue is greater than the maximum int value, then your loop will run forever because of this.

For example, if it's 2147483648, just as you think you're getting close to it, the int wraps around from 2147483647 back to -2147483648 and the loop just keeps on going.

like image 129
paxdiablo Avatar answered Oct 13 '22 14:10

paxdiablo


Apologies if this seems rude, but you will learn far more by trying this yourself.

Edited: aha, so you did try it, and got unexpected results. As has been explained elsewhere C-like languages tend to quietly wrap integer arithmetic. That's actually quite a reasonable behaviour in general if the cost of checking for overflow is high. Once you know that this can happen one codes carefully, especially watching for the kind of construct in your example.

like image 39
djna Avatar answered Oct 13 '22 13:10

djna