Search code examples
c++castingcomma-operator

Why cast the result of pre-incrementation to void in comma separator context?


Looking at std::for_each_n's possible implementation:

template<class InputIt, class Size, class UnaryFunction>
InputIt for_each_n(InputIt first, Size n, UnaryFunction f)
{
    for (Size i = 0; i < n; ++first, (void) ++i) {
        f(*first);
    }
    return first;
}

I noticed that the part where we typically see i++ (or, the preferred ++i) consists of two operations:

  • ++first
  • (void) ++i

separated by a comma. While most of it makes sense, the (void) cast seems a little surprising to me. All I can guess is that there could be an overloaded operator , that takes the deduced type of InputIt and Size which would result in some surprising side-effects. Could that be the reason? If yes, are we sure that cast to void solves that issue entirely?


Solution

  • Could that be the reason?

    Handling the evil overload of operator comma is indeed a good reason.

    I don't see other (valid) reasons.

    If yes, are we sure that cast to void solves that issue entirely?

    Yes, we cannot overload operator comma with void (neither with conversion to void).