Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of (void) first2++ here? [duplicate]

Tags:

c++

expression

On this page of en.cppreference there are examples of possible implementation of lexicographical comparison. Here is the basic one:

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);
}

IIRC lines like (void)some_argument; are commonly used to supress compiler warnings about unused parameters. But in this function, all parameters, including first2 are used - so what's the point of writing (void) first2++ in the for statement?

Is it some syntax workaround in case InputIt1 overloads operator,?

like image 275
Xeverous Avatar asked Apr 16 '17 16:04

Xeverous


1 Answers

It ensures that the built-in comma operator is used - just in case there is a user-defined overload that does something unexpected. A value of void type can never be passed to a function, so no such overload could be selected here.

Imagine otherwise what would happen if this function existed:

void operator , (InputIt1 const &, InputIt2 const &) { launch_missiles(); } 

EDIT: This is actually mentioned on the related cppreference discussion page.

like image 168
Alan Stokes Avatar answered Oct 12 '22 19:10

Alan Stokes