hn.today

Iterating Backwards in C

davidpriver.com5 points1 comments
Screenshot of Iterating Backwards in C

The piece explains how to iterate backward through a C array or buffer when the index has type `size_t`. A tempting loop that starts at `count - 1` and continues while `i >= 0` is incorrect: `size_t` is unsigned, so that condition is always true, and an empty range makes the initial value wrap to `SIZE_MAX`. Switching to a signed index can work, but it risks awkward conversions when the index is used with unsigned sizes, depends on `ssize_t` unless another type is provided, and can create width or promotion issues.

The recommended pattern is `for (size_t i = count; i--; )`. The post-decrement condition tests the old value, then decrements it before the loop body runs. Thus the body sees indices from `count - 1` down through zero, and an initial count of zero skips the body. When the condition tests zero, the decrement wraps the unsigned variable, but unsigned wraparound is defined in C and the loop ends before that value is used. The example applies this pattern to search for the last occurrence of a value, returning as soon as it finds a match. The central advice is to use this compact unsigned loop rather than converting the index to a signed type.

Read on davidpriver.com1 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.