Search code examples
c++iteratoroperator-precedence

Increment and ternary operator precedence in c++


I would like to print elements of a vector separated by semicolon. The following code snippet produces a strange result: the result starts with the second element of the vector. Can anybody write an explanation? When is the iterator incremented in this case?

#include <iostream>
int main() {
    vector<int> v(10);
    for ( int i = 0; i < 10; ++i ) {
        v[i] = i;
    }

    for ( auto it = v.begin(); it != v.end(); )
        std::cout << *it << ( (++it != v.end() ) ? ";" : "" );
}

Solution

  • Prior to C++17, the order in which *it and ++it are carried is unspecified. See, e.g., https://en.cppreference.com/w/cpp/language/eval_order

    This can be seen in an easier example

    #include <iostream>
    
    int main() {
        int i = 3;
        std::cout << i << ++i;
    }
    

    where my compiler (Apple LLVM with -Wall option) reports

    warning: unsequenced modification and access to 'i' [-Wunsequenced]
        std::cout << i << ++i;
                     ~    ^