r/C_Programming • • Oct 25 '26

Iterating Backwards in C

https://www.davidpriver.com/Iterating-backwards-in-C.html
93 Upvotes

43 comments sorted by

8

u/lehmagavan Oct 25 '26

If I already have count somewhere in the scope and I don't need it anymore, why not just:

while ( count-- ){}

2

u/david2ndaccount Oct 26 '26

Sure, that works too. But if you do need it afterwards, this is how to do it.

1

u/limitless_grow Oct 26 '26

That's a pattern that I'm using often for executing a loop 'count' times.
Anything else is more code and harder to read.
However, count shouldn't be an index than because moving backwards in memory is quite slow.

4

u/StaticCoder Oct 26 '26

Why is moving backwards in memory slow? There are no obvious cache issues. Also sometimes you just have to go backwards (though I agree there's no reason to do it by default)

1

u/limitless_grow Oct 26 '26

That depends on the hardware and the cache prefetching. On some platforms it doesn't works the same in both directions. Of course it's not a big issue because the hardware is pretty fast either.

3

u/glasket_ Oct 26 '26

Tl;dr: It probably doesn't matter on most machines now, but it could still be relevant on legacy hardware or for more niche compilers.


The bigger issue is likely to be compilers tbh. The exact optimizations can get finicky, and a reverse stride could probably screw with a "good" compiler in some edge cases, while the more niche platforms might have compilers that just don't even think about reverse stride.

For pretty much any modern x86 or ARM CPU I think it's likely to be negligible at the hardware level, if any asymmetry is even present at all. I'm not certain, but I'm pretty sure modern Intel and AMD chips allocate prefetch streams independent of direction. Before ~2010 they still allocated them differently, usually around 3:1 (e.g. 12 forward, 4 reverse), but since then I believe they just prefetch based on access patterns regardless of direction and the number of them has only kept increasing.

On simpler architectures without prefetching and caching the hardware matters even less; you might have a cycle difference depending on how the stride traversal is handled, but otherwise it mostly comes down to whether or not the compiler understands reverse stride the same as forward stride and can produce optimal code for both cases.

137

u/Humble-Captain3418 Oct 25 '26 • Bravo

My go-to is 

for (size_t i = n; i --> 0;)
   ...;

I.e. the infamous "down to" operator. 

47

u/aligrant Oct 25 '26

Thanks, I hate it.

9

u/Humble-Captain3418 Oct 26 '26

Don't worry, you will learn to love it.

13

u/aligrant Oct 26 '26

I’ve been doing C/C++ for 20+ years, I most assuredly will not.

5

u/TraylaParks Oct 26 '26

30 years here, and I still can't stand K&R formatting :)

3

u/Professional-Crow904 Oct 27 '26

Y'all are weak. This is how Mr. S. R. Bourne wrote the original shell.

10

u/LemonLord7 Oct 26 '26 edited Oct 26 '26

Oh lord… I feel so weirded out by it by I guess if I view it as (i--) > 0 I can kind of handle it.

Got some other C quirks you mind sharing?

17

u/Humble-Captain3418 Oct 26 '26

Oh boy, I have a lot of them.

I recently found out that you can make a script out of a C source file by putting this at the top:

#if 0
TMP=`tmpfile`
cc -o $TMP $0 && exec $TMP $@
#endif

Do what you will with that information.

A declaration like int foo(); declares that foo is function returning an integer and accepting any number of arguments. So foo(1, 2, 3); is legal there; you'll just have some head-scratching to do when you want to use those arguments... Except you can define int foo(int, int, int); and just never have the original declaration visible to the latter. Bugs, you say?

A common bug is forgetting to return from a function returning a value. No worries, though, because GCC has your back! GCC will return the value of the last assignment in that case, because GCC is helpful like that... But only if you're compiling without optimizations. With optimizations, you get 0.

Lastly, there's C metaprogramming, which allows you to define new control keywords, for example foreach. This requires a bit of head-scratching, which is why it's great that there's an article about it: https://www.chiark.greenend.org.uk/~sgtatham/mp/

7

u/glasket_ Oct 26 '26

Regarding int foo(), the behavior is removed in C23. foo() is now equivalent to foo(void). The correct way to handle arbitrary arguments now is foo(...) and the stdargs.h macros.

As for the failing to return a value, that's just UB. A function that returns a value but fails to do so isn't valid, hence GCC having differing behavior depending on optimizations. So not strictly a quirk of the language, but just something that the language doesn't consider as a valid program.

3

u/Humble-Captain3418 Oct 26 '26

Before C23, foo(...) is/was UB, so that's less than stellar for backwards-compatibility in older software. Sure, it needed to happen, but blegh. I'd rather hvae deprecated int foo() altogether (making it a warning + defined behaviour) and keep the foo(void) as the canonical "this function takes no arguments" signature.

I know the return behaviour is UB, but GCC is so popular, the mistake common and the behaviour so unexpected that it's good to be aware of it; especially since generally it will result in "something breaks in prod, but everything works in debug" type errors...

2

u/P-39_Airacobra Oct 27 '26

I love the idea that GCC came so close to implicit returns but just completely fucked it up lol

1

u/LemonLord7 Oct 26 '26

Oh sweet Neptune… O_O

I don’t fully understand int foo() taking any arguments? Could you maybe give an example? When might it be useful? And don’t we already have variadic arg functions like int foo(…)?

1

u/Humble-Captain3418 Oct 26 '26

Sure. With the above foo, we can call it as foo(1.0, "hello world", &foo); and the compiler may issue some gentle reminder that you probably shouldn't do that. I can't think of any particular use cases, but I'm sure you could do something fun with macros and nan-boxing.

1

u/Falcon731 29d ago

It’s never been useful - just historic.

The very earliest c compilers didn’t have enough memory to store the signature of every function in a program. So the pragmatic choice back then was to define an empty parameter list as meaning “don’t check the arguments - just trust this function is used correctly”.

The practice has been discouraged since C85, but backwards compatibility with any code written before then means it’s only recently been actually made an error.

2

u/FemaleMishap Oct 26 '26

I'm in the process of dusting off my C after being in Python for years, and this is both doing my head in, and absolutely fantastic. I love it.

2

u/Different_Panda_000 Oct 26 '26

I hate it but it really looks handy for when the terminal value is greater than zero.

3

u/Naeio_Galaxy Oct 26 '26

That is....... art ✨✨

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:

size_t i;
for (i = high; i > low; ) { --i;
	...
}
assert(i == low);

due to the assertion after the loop being more intuitive. Cheers.

7

u/skeeto Oct 25 '26

I'm quite stubborn myself and haven't tried out signed sizes.

Ah, this finally explains why I haven't (yet!) changed your mind.

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) { ... }

1

u/triconsonantal Oct 27 '26

Or better yet, -1 works as a limit if you test for (in)equality:

for (size_t i = count - 1; i != -1; --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.

21

u/Big-Rub9545 Oct 25 '26

Unsigned wraparound is well-defined, and has been so for a long time. The issue is with signed wraparound.

4

u/________-__-_______ Oct 25 '26

TIL, thanks

3

u/Rabbitical Oct 25 '26

Yeah it's common for tracking rotation for instance

0

u/[deleted] Oct 25 '26

[deleted] — view deleted comment

10

u/david2ndaccount Oct 25 '26

Mostly old habit to not need to include <stdbool.h>. If you’re using C23 you can just use bool, true and false directly.

1

u/Hoxitron Oct 25 '26

I like to also create my own macros for true and false and use those instead of just 1 or 0.

7

u/beephod_zabblebrox Oct 25 '26

why, stdbool.h exists

2

u/Hoxitron Oct 26 '26

For the same reason as above. I like to code in C89 for fun.

0

u/[deleted] Oct 25 '26

[deleted] — view deleted comment

3

u/david2ndaccount Oct 25 '26

In the loop body, i has already been decremented by the condition. So on the first iteration it is count - 1, then count - 2, etc. The final time the loop body is actually executed i will be 0 in the body of the loop. Then the next check will end the loop.

7

u/8d8n4mbo28026ulk Oct 25 '26

The i-- is executed before the loop body, so there's no off-by-one. Try this:

for (unsigned i = 10; i--; )
    printf("%u ", i);

You'll get: 9, 8, ..., 0. I think you proved OP's point that people often get this wrong (when using unsigned types), haha.

3

u/WeAllWantToBeHappy Oct 25 '26

Good lort. I think I've had enough Internet for today.

Maybe even too much. Code is fine.

0

u/[deleted] Oct 26 '26

[deleted] — view deleted comment

4

u/FemaleMishap Oct 26 '26

Oh that second solution just woke up some trauma from 25 years ago. C/Win32 app with a timber design engine in C, adapted from Fortran originally. The first developer to work on it, would prototype new code in bloody BASIC and then reimplement in oddly structured C. He sometimes transposed his goto statements. The debugging was miserable.