LOGBOOK

HELP

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 i is 0 and we do i--, it wraps to 4294967295 (UINT_MAX)
  • 4294967295 >= 0 is 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 - DELTA involves signed i and unsigned DELTA
  • Signed gets converted to unsigned (C's implicit conversion rule)
  • -4 as 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!

From Quiz: REVE1 / C Programming | Updated: Jul 10, 2026