News for hackers. Stuff that matters.
Re:Incrementing Vectors (2019) by cocoto on Friday September 23, 2022 @07:30AM (#32950440)
Serious question, why would you write the increment function differently than this simple one below?

void vector8_inc(std::vector<uint8_t> &v) { for (uint8_t &x : v) { ++x; } }

No need to deal with indices or pointers, no obfuscated code, no additional variables, only one clearly stated side effect (we don't need to update a local variable), reads like simple English. I personally don't like C++ (I prefer C) but why would you write C like code in C++?

Re:Incrementing Vectors (2019) by Gupie on Friday September 23, 2022 @09:12AM (#32951438)
You wouldn't. The article itself says:

"What about the range-based for loop introduced in C++11?

Good news! It works fine. It is syntactic sugar for almost exactly the iterator-based version above, with the end pointer captured once before the loop, and so it performs equivalently."

Re:Incrementing Vectors (2019) by nkurz on Friday September 23, 2022 @09:00AM (#32951313)
Seems like a fair question. At a glance, it produces the same code as Travis's preferred solution: https://godbolt.org/z/7oPhxEs5E. Anyone with more taste in C++ code able to answer? I'm more comfortable with C than C++, but this would be my preferred answer (if somehow knew in advance that it was going to produce good code).
Re:Incrementing Vectors (2019) by BeeOnRope on Friday September 23, 2022 @02:59PM (#32955728)
It's mentioned in the article (look for "What about the range-based for loop"): it works fine because it uses iterators under the covers which as local objects avoid the specific problem which occurs here.

This article isn't really meant to highlight something problematic about vectors in particular, but with C and C++ in general: that we actually rely on aliasing-based optimization in many cases and this optimization is fragile.

The basic operation here is simply indexing into an array stored in a struct which is quite common, even though you of course should prefer the range-based for this minimal example.

Re:Incrementing Vectors (2019) by amag on Friday September 23, 2022 @09:20AM (#32951550)
You wouldn't if all you want is to just increment all elements in a std::vector but for a more complex loop you might want the index...