5

In the implementation of std::ranges::transform in GCC's stdlibc++, why does the for loop iterator increment have a (void) cast?

for (; __first1 != __last1 && __first2 != __last2;
         ++__first1, (void)++__first2, ++__result)
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214

1 Answers1

8

This is because in C++ it is possible to overload the comma operator. The benefit of that still eludes me to this day, but that's not important right now. The important point is that it's possible.

The explicit void cast prevents unintended side effects from an unexpected invocation of an overloaded operator here, with unwanted results. Note how a single void cast effectively prevents the comma operator on both the left and the right side from getting invoked.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • To be clear: both comma operators are applied, but they're the built-in comma operator. It's user-defined overloads that don't get applied. The `void` poisons them, because overloaded operators are functions, and you can't pass `void` as an argument to a function. – Pete Becker Jun 09 '21 at 15:17