LOGBOOK

HELP

Quiz Entry - updated: 2026.07.10

When should you use unsigned types in C?

Reach for unsigned when you genuinely want wrap-around modular arithmetic or are treating the value as a bag of bits (masks, flags, logical shifts) — not merely because a number "can't be negative".

DO use unsigned for:

  1. Modular arithmetic (multiprecision arithmetic)

    • When you want wrap-around behavior
    • Cryptographic operations
  2. Bit manipulation (treating as bit vectors)

    • Logical right shift (no sign extension)
    • Flag fields, bitmasks
    • Network protocols, binary formats

DON'T use unsigned for:

  1. Loop counters - Can cause infinite loops:

    // INFINITE LOOP!
    for (unsigned i = n-1; i >= 0; i--)
    // When i reaches 0 and decrements, it wraps to UINT_MAX
    
  2. Sizes that might be compared with signed - Mixed comparisons are dangerous:

    // Always false if len is unsigned!
    if (len < 0)
    
  3. Just because "it can't be negative" - The dangers outweigh the benefits

Best practice: Use size_t (unsigned) for array indices and sizes, but be careful with decrementing loops. Use ssize_t (signed) when -1 might indicate error.

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