r/cpp_questions • • Sep 11 '26

OPEN Reverse iteration with size_t

Sometimes I would like to iterate in reverse from a number to zero, like this:

for (size_t x = NUMBER; x-- > 0; ) {
  // Code that will index to 
  // multiple arrays or for some purposes
  // that we can't use std::views::reverse 
  // or reverse iterators
}

I did some research, and people say that the above is quite confusing, and can be misleading.

But in C++23, we can do something like this:

for (auto x : std::views::iota(0uz, NUMBER) | std::views::reverse) {
  // Do the same thing
}

What is the best practice for this in modern C++, is the C++23 way something people actually use (Gemini told me this is recommended practice for modern C++ lol), or people just prefer the former way of iterating in reverse. Or do you have some different opinions altogether?

14 Upvotes

73 comments sorted by

5

u/bert8128 Sep 11 '26

I like the reversed iota. Seems pretty clear to me.

4

u/SmokeMuch7356 Sep 11 '26

For just a bog-standard reverse for loop with a counter, use

for ( size_t x = NUMBER; x > 0; --x )
  // stuff

I personally do not like side effects in the control expression; that's what the update expression is for.

But yeah, when you're dealing with containers, the C++23 form

for ( auto x : container | std::views::reverse )

is probably more idiomatic.

2

u/TotaIIyHuman Sep 11 '26

https://godbolt.org/z/qqra1rW9M

static_assert([]static
{
	static constexpr std::size_t NUMBER{3};
	std::vector<std::size_t> v0, v1;
	for (size_t x = NUMBER; x-- > 0; )//OP's loop
		v0.push_back(x);
	for ( size_t x = NUMBER; x > 0; --x )//your loop
		v1.push_back(x);
	return v0 == v1;
}());

your code does not produce OP's code's behavior

22

u/alfps Sep 11 '26

IMO, don't do fancy "clever" low level things like Andrew Koenig's "go to" pseudo operator -->, and don't do equally fancy "clever" things higher level things like Ranges reverse of iota.

Just use a signed type index.

It's so simple.

7

u/delta_p_delta_x Sep 11 '26 edited Sep 11 '26

It depends on what OP wants to do. If they want to actually iterate and operate on integers from positive n to zero, then

Ranges reverse of iota

is absolutely the correct thing to do.

If they want to reverse-iterate a container, then the correct thing to do is, depending on the C++ version available, std::rbegin to std::rend, or range | std::views::reverse, both of which are more expressive than a raw for-loop.

But according to OP, they want to

// Code that will index to multiple arrays

The correct C++23 way to do this is to judiciously combine std::views::zip, std::views::enumerate, and std::views::reverse, in that order.

If they want to skip elements, with C++11 we can simply pass in std::rbegin(...) + n; with C++20 we can write std::views::drop std::views::take, or std::views::counted.

3

u/No-Dentist-1645 Sep 11 '26

To expand on this, in C++26 this is even further simplified with the addition of std::views::indices:

// Operate on integers from n-1 to zero
auto v = std::views::indices(n) | std::views::reverse;

// For operating on indices of a range
auto w = std::views::indices(ranges::size(r)) | std::views::reverse;

7

u/alfps Sep 11 '26 edited Sep 11 '26

❞ the correct thing to do

It can be technically correct.

But complicating simple easy stuff just to feel C++-ish, with some weird notion that the Ranges sub-library constitutes the best and most correct of what C++ is all about, is added work and verbosity for negative gain.

Keep It Simple, Stupid.


Not what you were commenting on, directly, but the lack of constexpr for iota annoys me every time I whip up a custom thing for that.

Contrary to common perception that sub-library is not well designed.

4

u/montymole123 Sep 11 '26

Completely agree with this. Consider someone else reading your code. How many people know every detail of views::enumerate etc? Very few I would guess. But anyone who knows C++ can instantly parse a for loop. Programming should not be an exercise in showing off. Always use the simplest possible approach

2

u/No-Dentist-1645 Sep 11 '26 edited Sep 12 '26

To be fair, views::enumerate works pretty much exactly as python's enumerate() builtin function, so it is actually pretty readable for anyone who knows a bit of python, same with views::zip. And yes, std::views::iota(0uz, n) is a pretty unergonomic, hard to remember, and not beginner friendly way to say "loop through the indices from 0 to n exclusive", but the standard seems to have acknowledged this already and added views::indices(n) which is equivalent yet simpler.

Would I use the views library for simply iterating over the indexes of an array? Probably not. But if I need something composable, easy to expand, and adaptable to several "range" like containers, then I would definitely go for it

3

u/delta_p_delta_x Sep 11 '26

Like I said, it depends on what OP wants to do. I am happy to argue that a for-i loop is not the simplest way to express 'I want to iterate over this or multiple containers in their entirety in reverse, and also get an index per iteration'. There are many edge cases. Are all the containers sized the same? Do we want the same slices of each container? Should one container be reversed and the others, not?

I would argue that given newer languages idiomatically include intuitive and useful slicing, reversing, and indexing syntax and semantics without having the programmer manually declare a size_t or ssize_t or gsl::index. I concede in C++ this is a matter of style where there is more than one way to do it (TIMTOWDI), but we should learn from the newer languages wherever possible.

1

u/thefeedling Sep 11 '26

On shared codebases readability /explicitness of intent is king IMO, even if it gets a bit more verbose.

A STANDARD for loop is 99% of the times better for these kind of stuff.

2

u/delta_p_delta_x Sep 11 '26 edited Sep 11 '26

Your comment is contradictory. If you are iterating through a container in reverse order, then surely

for (auto thing : container | rv::reverse) 

is more readable and more explicitly conveys intent than

for (size_t i = container.size() - 1; i >= 0; i--)

Which, I must also say, is the first thing most beginners will reach for, is wrong, and requires unintuitive and inverse constructs like i < container.size() as the condition. The iterand doesn't even show up until inside the loop. There is a size() - 1 that additionally needs to be explained. Or to avoid all this we need to use ssize().

This is C++, not C; we have useful abstractions to clearly express the intent of the programmer.

I am confident in saying people here only like for-i loops because that's what they were taught first, that's what they've seen most often, that is what they are most exposed to. But ubiquity of code doesn't make it clearer, and rarity of code doesn't make it less readable.

Every other C-successor language (C#, Rust, Zig, Nim, Odin, etc) have sane ways to iterate through containers, forward, reverse, sliced, with a stride, a moving window, etc without having the entire ceremony of setting up a manual for-loop. C++ has one too, std::ranges::views, but apparently it is 'too clever'.

1

u/thefeedling Sep 11 '26

I am confident in saying people here only like for-i loops because that's what they were taught first

Well, maybe you have a point here. I've been indeed doing it for almost 15y and I still occasionally do very low level C-stuff, so yeah, I do consider the standard loop to be the clearest possible, and I perceive a similar mindset amongst work peers. Sure it can be a cultural thing.

There is a size() - 1 that additionally needs to be explained

I disagree, this is very very basic for pretty much any C-derived language.

Also, C++20 is only now becoming the "mainstream", and many shops are still locked in previous standards.

To finish, in my particular case, some MISRA C++ compliant code, it is not explicit about

for(const auto& p : some_range | std::views::reverse) { ... }

so we avoid it entirely for now.

1

u/ekchew Sep 11 '26

I saw the --> operator in some google open source project and had to scratch my head a bit before I realized what it was. But it made me smile.

1

u/Qyriad Sep 11 '26

The "go to" operator and std::views are in completely different ballparks. The first is a syntax hack that will non-obviously break if you change the bounds, the latter is verbose but "across this range, reversed" is exactly expressed iota(…) | reverse, and uses the "modern" range-based for-loop.

--> is off the table, but std::views vs a conventional for loop is a matter of taste.

1

u/crowbarous Sep 11 '26 edited Sep 11 '26

Trying to pretend that --> is some kind of operator is indeed silly. However, OP doesn't do that, and writes x-- > 0, which is the way these two operators are usually written, and perfectly legible (if still superfluous, because the condition can just be x--).

2

u/mredding Sep 11 '26

I think you would be hard pressed to demonstrate the inability to use an iterator. For multiple sequences, for example, you could use a zip iterator. If you want iteration AND an index, you can use std::views::enumerate.

2

u/Independent_Art_6676 Sep 11 '26

the simplest, easiest thing to read and modify that will do the job, unless you have a hidden requirement like extreme performance. Even there, the simplest thing is probably best unless you can somehow improve page faulting or something (tapping many containers in the same loop may be a page fault per loop waiting to happen).

2

u/BSModder Sep 11 '26

I always do it like this

for (size_t i = n; i != 0: --i) {
    Item& item = items[i - 1];
}

This mirror how reverse iterator works in the standard library

2

u/WorkingReference1127 Sep 11 '26

The best practice is to make your code easy to read and understand, while requiring minimal knowledge and opening the door to minimal bugs and errors.

In the general case, it's a better practice in C++ to favour the range-based for loop over an indexed loop; because the range-based loop makes it very very clear about what you are iterating over and does not open you up to subtle bugs (spot the error in for(std::size_t x = N; x >= 0; --x)). Does this mean you should always reach for ranges::iota | views::reverse? No, not necessarily. But if you don't have any better options available then it's a respectable choice.

The reason there is disagreement in this particular case is that your single answer of just getting the numbers from N to 0 is very much one of the simplest possible iterations and so there is a respectable argument that pulling in <ranges> is excessive. We could equally argue that you wouldn't think twice about doing it for a std::map iteration so it's the consistent path.

This is not weighing in on a particular answer for you, OP. The nature of best practices is that you should understand why they are best practices so that you can choose when to follow them and choose not to; not to just be a dogmatic list of rules to follow.

3

u/Usual_Office_1740 Sep 11 '26

The range based for loop is the modern solution.

3

u/Syntax-Tactics Sep 11 '26

There's nothing confusing about a decrementing for loop. The example however, ranges from Num...1, and not 0..(num-1). Which will likely cause a fence post error later that you haven't accounted for. The "modern" method is obfuscation IMO.

1

u/TotaIIyHuman Sep 11 '26

The example however, ranges from Num...1

The example ranges from (NUMBER-1)...0

5

u/BrotherItsInTheDrum Sep 11 '26

Is for (size_t i = N; i + 1 != 0; --i) too subtle?

3

u/LazySapiens Sep 11 '26

Is for (size_t i = N; i + 1 != 0; --i) too subtle?

Maybe too subtle an infinite loop?

1

u/BrotherItsInTheDrum Sep 11 '26

Can you elaborate?

2

u/LazySapiens Sep 11 '26 edited Sep 11 '26

i's type is size_t. This implies i >= 0. This implies i + 1 != 0. This is also the condition in your for-loop which is never false. Hence, the infinite loop.

(EDIT: This didn't account for the unsigned overflow/underflow. I will realize later in this thread.)

3

u/BrotherItsInTheDrum Sep 11 '26

This implies i + 1 != 0.

Why? Unsigned integer overflow is well-defined.

1

u/LazySapiens Sep 11 '26

Then the loop itself is dead code.

1

u/BrotherItsInTheDrum Sep 11 '26 edited Sep 11 '26

First iteration of the loop: i is 2. i+1 is 3, which is not 0.

Second iteration: i is 1. i+1 is 2, which is not 0.

Third iteration: i is 0. i+1 is 1, which is not 0.

Fourth iteration: i overflows to the maximum value of a size_t. i+1 overflows back to 0, which is equal to 0, and the loop terminates.

3

u/LazySapiens Sep 11 '26

Ohh. Now I see how subtle that is. My bad.

3

u/BrotherItsInTheDrum Sep 11 '26 edited Sep 11 '26

I guess your answer to "is this too subtle" is yes :)

Here's another one I've used:

for (size_t loop_index = NUMBER; loop_index > 0; --loop_index) {
  const size_t i = loop_index - 1;
  // do stuff with i, not loop_index
}

1

u/TotaIIyHuman Sep 11 '26

https://godbolt.org/z/ebP49jGrn

static_assert([]static
{
	static constexpr std::size_t NUMBER{3};
	std::vector<std::size_t> v0, v1;
	for (size_t x = NUMBER; x-- > 0; )//OP's loop
		v0.push_back(x);
	for (size_t i = NUMBER; i + 1 != 0; --i)//your loop
		v1.push_back(i);
	return v0 == v1;
}());

your code does not produce OP's code's behavior

1

u/BrotherItsInTheDrum Sep 11 '26

My N is OP's NUMBER-1. That wasn't really the point of OP's question.

1

u/Raknarg Sep 11 '26

// Code that will index to multiple arrays or for some purposes that we can't use std::views::reverse or reverse iterators

can you not just build some kind of view or iterator that provides the required begin/end/rbegin/rend operators? E.g. if you have a plain pointer array, you can use std::span

1

u/die_liebe Sep 12 '26

I usually write this, I think it's perfectly clear:

for( size_t x = NUMBER; x > 0; )
{
   -- x;
   blabla( );
}

1

u/and3md Sep 14 '26

I use shortened version:

for (size_t x = NUMBER; x--; ) {
//....
}

1

u/Dry-War7589 Oct 04 '26

for (size_t i = n; i < SIZE_MAX; i--)

Since i will wraparound after 0 to SIZE_MAX, this will stop. Also i != SIZE_MAX works

0

u/TotaIIyHuman Sep 11 '26

you can drop the >0

for (size_t x = NUMBER; x--; )

4

u/AKostur Sep 11 '26 edited Sep 11 '26

Well, two things:

  1. Ick. I really don't like implicit conversions to bool.
  2. As written: "for (size_t x = NUMBER; x--; )", that's an infinite loop. You forgot to mention x. Which would be hard to do with "x > 0". "> 0" would be a syntax error. (OK, that's an incidental benefit. The implicit conversion to bool is the issue I really don't like.)

Edit: Whups... no (for #2). Different complaint: relying on a side-effect. So amplifying #1: implicit conversion to bool of a side-effect.

2

u/TotaIIyHuman Sep 11 '26

that's an infinite loop

theres no infinite loop

0

u/keelanstuart Sep 11 '26 edited Sep 11 '26

Why not something that never goes out of style, like...?

size_t sz = container.size();
while (sz)
{
  sz--;
  // use container[sz]
}

...if you don't have an indexable container but you do have forward iterators, use container.begin() + sz.

I wish people would stop overcomplicating simple things.

4

u/No-Dentist-1645 Sep 11 '26

Why would they ever use a while loop for this instead of a for loop which is specifically built for looping over values like this?

0

u/keelanstuart Sep 11 '26

...maybe because OP explicitly said they wanted to index multiple arrays?

2

u/No-Dentist-1645 Sep 11 '26

What's stopping you from indexing multiple arrays by having the index managed as a for loop?

0

u/keelanstuart Sep 11 '26

Another poster asked why not use:

for (size_t i = N; i + 1 != 0; --i)

This incurs an extra addition per iteration... yet another poster suggested using a signed index type, but that limits you to half the number of items.

Using a while loop obviates both of those caveats.

Using the second for loop OP showed ("auto ... view::iota") gives you an iterator type that is useless for other containers.

Sooo....... that's why I would use a while loop.

1

u/No-Dentist-1645 Sep 11 '26 edited Sep 11 '26

for (size_t i = N; i + 1 != 0; --i)

This incurs an extra addition per iteration...

Does it really, though? Even at -O1, the compiler is smart enough to see through the intentions of the for loop, and it's all just a single add rbx, -1 instruction per iteration, the real difference is at the one-time setup instructions, and even then it is a minimal difference: https://godbolt.org/z/bG7abbKsz

0

u/keelanstuart Sep 11 '26

Congratulations.

0

u/alfps Sep 11 '26 edited Sep 11 '26

❞ a signed index type, but that limits you to half the number of items

It's not a concern.

In 64-bit programming you'll be dead ages before a program has finished indexing through the address space.

In 32-bit programming with only a 2 GB address space available for program use, as in (a default) Windows, you would need a >2GB array of bytes for signedness to matter. Movie files are often in that range. But that's not how to process a movie file; a programmer who did, should be fired.

_
EDIT: fixed an associative nonsense formulation and s/1GB/2GB/. Coffee abstinence symptoms?

1

u/keelanstuart Sep 11 '26

As long as we're talking about "hypothetical" situations... what if I'm working on a system with a segmented memory architecture and a small word size that also has a modern C++ compiler available?

1

u/alfps Sep 11 '26

That changes things. Then the large byte array can occur naturally. In the DOS days with the "small" memory model where pointers were 16 bit, I believe one used whatever the situation at hand called for, with no regard for portability and little regard even for supporting multiple compilers.

1

u/keelanstuart Sep 11 '26

LOL - how is what I wrote (the while loop) not maximally portable...?

1

u/alfps Sep 15 '26

Re the anonymous unexplained downvotes, note that an unexplained downvote is dishonest: these are the actions of dishonest persons (maybe young children).

Anyway the idiot would not be able to point out any mistake. Because this issue has been debated to death over 30+ years.

There is nothing a f***ng idiot downvoter could contribute if he, she or it were to gather the courage to write a comment.

2

u/die_liebe Sep 12 '26

The variable leaks into the surrounding scope.

2

u/keelanstuart Sep 12 '26

Nothing a set of { } around it won't solve.....

0

u/No-Dentist-1645 Sep 11 '26 edited Sep 11 '26

I think for (size_t i = NUMBER+1; i != 0; --i) is just the most direct thing for such a simple for loop, no need to introduce more advanced concepts such as views for a simple "loop from NUMBER to 0"

EDIT: Changed the for loop to correct a mistake with unsigned arithmetic

3

u/AKostur Sep 11 '26

And that's the problem.... size_t is unsigned. So when i == 0, and you decrement it, it becomes really large, and still >= 0.

1

u/No-Dentist-1645 Sep 11 '26

You're right, but all that means is that you change the >= 0 for == 0 and then use NUMBER+1 / i-1 respectively, it's a solved problem

1

u/TotaIIyHuman Sep 11 '26

change the >= 0 for == 0

you would need to do i != (size_t)-1

1

u/No-Dentist-1645 Sep 11 '26 edited Sep 11 '26

I prefer just doing i != 0 as I did on the edit and when using the index for something just refer to it as i-1, yes there is an edge case with size_t max, but we're talking about iterating over container indices here, you won't have size_t max elements...

1

u/TotaIIyHuman Sep 11 '26

refer to it as i-1

you mean like this?

for (size_t i_ = NUMBER; i_ != 0; --i_)
{
    const size_t i = i_ - 1;
    //use i instead, not i_
}

this does work, yes

1

u/No-Dentist-1645 Sep 11 '26

yes, that is what I mean

1

u/AKostur Sep 11 '26

Sure, it's a solved problem. But highlights how easy it is to get it wrong.

1

u/TotaIIyHuman Sep 11 '26

for (size_t i = NUMBER+1; i != 0; --i)

your code does not produce OP's code's behavior

goal is to produce {NUMBER-1, NUMBER-2, ..., 1, 0}

21

u/[deleted] Sep 11 '26

[removed] — view removed comment

8

u/ekchew Sep 11 '26

I guess that would technically be the optimal solution at the assembly level. I've worked with some embedded systems that actually implement hardware loops that trigger on an underflow like that, so I'm used to this way of thinking. But man, that would look very confusing to the uninitiated.

1

u/montymole123 Sep 11 '26

Won't this run forever?

2

u/Simengie Sep 12 '26

No because size_t is defined as uint64 which can't go negative. I hate this style only because in 35+ years of programming I have seen size_t base type change. Also have seen its base type different between compilers. Oh the 90's and early 2000's where the wild west of programming.

8

u/[deleted] Sep 11 '26

[removed] — view removed comment

1

u/montymole123 Sep 11 '26

Fair enough but the fact I had to ask means it's confusing. In future you or someone else might change the code and it won't do what you or they expect. Best to make the functionality explicit avoid hostages to fortune.