You are not logged in.

#1 2014-09-29 09:26:29

ezzetabi
Member
Registered: 2006-08-27
Posts: 947

Loop on an array backward, how do you it?

A simple, no-frills array. So do not think to reversed iterators, interfaces or other "advanced" stuff...

The indexes are, of course, from 0 to arr_size - 1.

(a) for (i = arr_size; i > 0;) { --i; /* the code */ }
(b) for (i = arr_size - 1; i >= 0; --i) { /* the code */ }
(c) for (i = arr_size; i-- > 0;) { /* the code */ }
(d) for (i = arr_size; i--;) { /* the code */ }
(e) for (j=0; j < arr_size; ++j) { i = arr_size - 1 - j; /* the code */ }

(f) other, explain

All those approaches work (eventual typos a part), I was curious to know how you would do it..

Offline

#2 2014-09-29 09:48:18

progandy
Member
Registered: 2012-05-17
Posts: 5,307

Re: Loop on an array backward, how do you it?

If you go for readability, I'd use (b).
For optimized code I might be persuaded to (c) for signed or (d) for unsigned i.
(e) is too much work without gain. Use it only if you need i and j at the same time.
(a) looks nice, but it implies thar the decrement is not constannt between all  iterations and has no other advantages over (c), so I'd choose it if I jump around a lot.


| alias CUTF='LANG=en_XX.UTF-8@POSIX ' | alias ENGLISH='LANG=C.UTF-8 ' |

Offline

#3 2014-09-30 14:22:52

ezzetabi
Member
Registered: 2006-08-27
Posts: 947

Re: Loop on an array backward, how do you it?

I am not sure... (c) and (d) are pretty much the same; (b) does not work for unsigned (i>=0 is always true), so definitely you won't use it in that case.

For raw efficiency (a) has a small advantage, since it uses prefix instead of postfix it saves few assembly lines. However I hardly believe it matters.

See  this small C function:

int f(int* arr, int arr_size) {
    for (int i = arr_size; i--;) {
        arr[i] = -17;
    }
}

It uses (d) imagine the same function using (a). In my system the diff between the two assembly generated by gcc is:

 % diff a.s b.s
[(filename related stuff removed)]
18a19
>       subl    $1, -4(%rbp)
26,29c27
<       movl    -4(%rbp), %eax
<       leal    -1(%rax), %edx
<       movl    %edx, -4(%rbp)
<       testl   %eax, %eax
---
>       cmpl    $0, -4(%rbp)

Last edited by ezzetabi (2014-09-30 15:24:17)

Offline

Board footer

Powered by FluxBB