Range-based for loop

From vegard.wiki
Revision as of 17:35, 29 February 2020 by Vegard (talk | contribs) (new page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

One of my pet peeves is the regular counting for loop in C where you have to repeat the variable name 3 times. This is error-prone in the case of nested loops, since the compiler has no way to know that you meant to increment j and not i. To prevent this kind of error, you can use a few helper macros that iterate over a range (forwards or backwards).

Definitions:

#define RANGE(var, low, high) \
        (typeof(0 ? (low) : (high)) var = (low), _end = (high); var < _end; ++var)

// https://stackoverflow.com/a/5458283
#define REVERSE_RANGE(var, high, low) \
        (typeof(0 ? (low) : (high)) var = (high), _end = (low); var-- > _end; )

Note that typeof is a GNU/gcc extension, so this will not work on e.g. MSVC.

Usage:

for RANGE(i, -1, 5) {
        printf("%d\n", i);
}