logoalt Hacker News

kooi • today at 3:16 AM • 2 replies • view on HN

As long as you make sure the end points are valid, this is most intuitive for me. Just using i as a backwards step.

for (int i = 1; i <= N; i++) {

    array[N-i]

}

Replies

eps • today at 8:38 AM

Conventionally, loops with <= is very much a Pascal thing, not C.

sltkr • today at 3:41 AM

This fails on overflow: if N == INT_MAX then your loop doesn't terminate and actually invokes undefined behavior in C.

The safe way to write it is:

    for (int i = 0; i < N; ++i) {
        something(array[N - 1 - i]);
    }
(or with size_t instead of int depending on the type of N)