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

1

8

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,?

Introversion answered 16/4, 2017 at 16:30 Comment(0)
M
5

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.

Mats answered 16/4, 2017 at 17:0 Comment(1)
Isn't that what happened with the MOAB a couple of days ago?Lauralauraceous

© 2022 - 2024 — McMap. All rights reserved.