Quiz Entry - updated: 2026.07.10
Why is using unsigned for loop counters often dangerous?
An unsigned counter can never be negative, so a "for (i = …; i >= 0; i--)" loop never ends — when i hits 0 and decrements, it wraps around to a huge value instead of going below zero.
Bug example 1 - Simple decrement:
unsigned i;
// INFINITE LOOP!
for (i = cnt-2; i >= 0; i--)
a[i] += a[i+1];
Why it's broken:
- When
iis 0 and we doi--, it wraps to4294967295(UINT_MAX) 4294967295 >= 0is always true!- The loop never ends
Bug example 2 - Subtle sizeof trap:
// sizeof returns size_t (unsigned!)
#define DELTA sizeof(int)
// signed
int i;
for (i = CNT; i - DELTA >= 0; i -= DELTA)
// ...
Why it's broken:
i - DELTAinvolves signediand unsignedDELTA- Signed gets converted to unsigned (C's implicit conversion rule)
-4as unsigned becomes a huge positive number!
Safe alternatives:
// Option 1: Use signed types for counters
for (int i = cnt-2; i >= 0; i--)
// Option 2: Check before decrementing
// Wrapping makes i > cnt
for (unsigned i = cnt-1; i < cnt; i--)
// Option 3: Count up instead
for (unsigned i = 0; i < cnt-1; i++)
a[cnt-2-i] += a[cnt-1-i];
Rule of thumb: Use size_t for sizes and indices, but be careful with loops that decrement!