WarriorJoe
WarriorJoe

Reputation: 41

Using comma in for loop

template <class _InputIterator, class _OutputIterator>
inline _LIBCPP_INLINE_VISIBILITY
_OutputIterator
__copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
{
    for (; __first != __last; ++__first, (void) ++__result)
        *__result = *__first;
    return __result;
}

I have taken the above code from the standard template library, what does the common mean? Is it casting? Similar to initialising multiple statements? But in this case casting

Upvotes: 0

Views: 199

Answers (1)

Pete Becker
Pete Becker

Reputation: 76438

The issue is that someone might have created a funky iterator type with an overloaded comma operator:

struct my_funky_iterator {
    // various normal iterator operations
    my_funky_iterator operator,(my_funky_iterator) const;
};

With that overload, the expression

++__first, ++__result

increments the two iterators and then calls the overloaded comma operator on the result. That ought to be harmless, but someone who would overload the comma operator here would also not worry about doing terrible things inside that operator.

So the code adds that cast, to avoid calling a possible overloaded comma operator:

++__first, (void)++__result

Now the compiler looks for a comma operator that takes my_funky_iterator as its first argument and void as its second argument. The only way to do that is to convert the first argument to void and use the built-in comma operator, as if the expression had been written

(void)++__first, (void)++__result

When you write your own algorithms it's up to you whether this degree of paranoia is appropriate. (you might like to replace "paranoia" with "caution" in the preceding sentence)

Upvotes: 2

Related Questions