# How to detect overflows within a for loop

Printable View

• 04-06-2011
Richardcavell
How to detect overflows within a for loop
Hi, everyone. I have the following loop:

Code:

unsigned int i;
const unsigned int max = 10;
bool ignoremax = // true or false
for (i=1;i<max || ignoremax; i++)
{
printf ("This is loop number %d\n", i);
}

Now, what I want is to detect when i has overflowed and prevent it from wrapping around and giving misleading output within the loop. What's the most elegant way to do this? Is this acceptable or hacky?

Code:

unsigned int i;
const unsigned int max = 10;
bool ignoremax = // true or false
for (i=1;i<max || ignoremax; if (i) i++)
{
if (i) printf ("This is loop number %d\n", i);
else
printf ("We've lost count\n");
}

• 04-06-2011
Adak
It's usually an error to start i at 1, in C.

Code:

for(i=0;i<MAX;i++) {
if(i>=BadNumber)
break;
array[i] = (2x + y ) * 2; //normal processing
printf("\nThis is loop number %3d", i+1); //i starts at zero, but here, for human "consumption", it's i+1

}

• 04-06-2011
Subsonics
Since both 'i' and 'max' are the same type and the condition is:

Code:

i < max
how can 'i' become larger than max?
• 04-06-2011
Richardcavell
ignoremax
The test is i<max || ignoremax. My idea is that the loop goes a certain number of times, unless the user desires to have it loop infinitely. That's why i can overflow.

Richard
• 04-06-2011
grumpy
If an unsigned variable becomes zero after incrementing, overflow has occurred. Wrapping (probably better described as confirming to modulo rules) is a basic property of unsigned types.
• 04-06-2011
FrankTheKneeMan
Well, if you're starting at 1, then you could always make your loop condition (i && (i<max || ignoremax)), then once you've lost count, and looping is unnecessary anyway, you could break from the loop.

Really, it depends on what processing you're doing within the loop.
• 04-06-2011
CommonTater
Quote:

Originally Posted by Richardcavell
Hi, everyone. I have the following loop:
Now, what I want is to detect when i has overflowed and prevent it from wrapping around and giving misleading output within the loop. What's the most elegant way to do this? Is this acceptable or hacky?

Now the bad news... You can't do that in C or any of it's cousins.

The C language does not include range checking. It is up to you as a programmer to avoid situations where an integer overflow might occur.