Search code examples
c++for-loopc++11void

Why (void) between two comma separated statements in a for loop


The following code comes from an implementation example of std::lexicographical_compare on cppreference.com:

template<class InputIt1, class InputIt2>
bool lexicographical_compare(InputIt1 first1, InputIt1 last1,
                             InputIt2 first2, InputIt2 last2)
{
    for ( ; (first1 != last1) && (first2 != last2); ++first1, (void) ++first2 ) {
        if (*first1 < *first2) return true;
        if (*first2 < *first1) return false;
    }
    return (first1 == last1) && (first2 != last2);
}

Why is there a (void) in the loop, and what would be the consequence of not putting it there?


Solution

  • If the type of the value returned by prefix increment operator of InputIt1 type has overloaded comma operator then expression ++first1, ++first2 may invoke it, so casting result of ++first2 to void ensures that no overloaded comma operator is invoked since overloaded comma operator can not accept void as parameter.