r/C_Programming • u/david2ndaccount • Oct 25 '26
Iterating Backwards in C
https://www.davidpriver.com/Iterating-backwards-in-C.html
93
Upvotes
r/C_Programming • u/david2ndaccount • Oct 25 '26
8
u/lehmagavan Oct 25 '26
If I already have
countsomewhere in the scope and I don't need it anymore, why not just:137
u/Humble-Captain3418 Oct 25 '26 •
My go-to is
I.e. the infamous "down to" operator.
17
u/8d8n4mbo28026ulk Oct 25 '26
Nice and concise. Such corner cases are a good reason against unsigned sizes, though I'm quite stubborn myself and haven't tried out signed sizes.
I tend to prefer this variant:
due to the assertion after the loop being more intuitive. Cheers.
3
u/runningOverA Oct 25 '26
Very helpful. Learned something new after being a long time follower of this sub.
4
u/zellforte Oct 26 '26
i < count invariant works for backwards loops as well (requires unsigned types), this is how I do it:
for(size_t i=count-1; i<count; --i) { ... }2
u/Zirias_FreeBSD Oct 28 '26
Reminds me a lot of this recent discussion. I'd still say the solution labeled the "correct one" here is kind of obfuscated. Code doing simple things should be immediately obvious, so, that's a weakness. Nevertheless, agreed it's the best of not-so-great options.
But you'll certainly find different opinions, starting with the question whether an index should be signed or unsigned.
One thing that's missing: For people going with signed indices, there's a standard C alternative to POSIX'
ssize_t:ptrdiff_t. Semantics are slightly different, but at least it's obvious that a type that can store any possible difference of pointer values can also store any possible size.1
u/Different_Panda_000 Oct 26 '26
I just never spent the time to find out or figure out a proper way to do this reverse iteration.
Now I have some work to do in a code base I'm maintaining. I'm pretty sure over the years and the multiple people working in it there are places where this needs to be done.
-1
u/________-__-_______ Oct 25 '26
Since when is unsigned wrapping well defined? I was under the impression overflow was UB unless you use the C23
ckd_sub.0
u/[deleted] Oct 25 '26
[deleted] — view deleted comment
0
u/[deleted] Oct 25 '26
[deleted] — view deleted comment
0
u/[deleted] Oct 26 '26
[deleted] — view deleted comment