Lets assume the code doesn't need the index, but something interesting happened during debugging and I want to know the position of the item in the container.
for (int item : myarray)
doSomething(item); // <-- breakpoint/exception/assertion; what index was 'item'?
Lets assume it's a random access containers where it should still be resonable to find the answer at runtime. Is this possible? Can it be possible?
It'd be really convenient if we could e.g. hover over for
and see the current iterator and its distance to the container's begin().
If item
were a reference I could make a risky guess that the index is &item - &myarray[0]
. Although it'd be a pain to type every time I wanted to check during debugging.
To clarify, there are many questions about getting the index in the code (interesting references here and here). Instead I want the index in the debugger. Maybe I didn't write the code, can't easily recompile or a repro is highly intermittent. It's perfectly reasonable to not want the index in the code because it can add clutter and confusion when it's not needed. Constructs such as std::views::zip
and std::views::enumerate
will make working without indices easier. That said, we currently lose debugging information when buying into these features.
for
loop gives the compiler a lot of leeway with indices and limits.range-for
loops use iterators only, not indexes. There is no index for the loop's assembly code to keep track ofstd::deque
would be a typical non-trivial case. It has O(1) distance, but the debugger would need to calculate that on demand. Conceptually feasible, but quite a bit of work to implement.item
. If you can pull all properties of that object, you can write a unit test in which you calldoSomething(item)
and reproduce the problem without a loop. No need for the index.