Casperon
Casperon

Reputation: 7

C++ Operator Precedence while using vector iterator

Why does the next program prints 1 instead of 4?

std::vector<int> v;
v.push_back(1);
v.push_back(4);
std::vector<int>::iterator it = v.begin();
int n = *(it++);
std::cout << n;

Upvotes: 0

Views: 144

Answers (1)

Chris Uzdavinis
Chris Uzdavinis

Reputation: 6131

The pre/post increment operator is part of an expression that evaluates to a value (and has a side effect of changing the variable being incremented.)

Evaluation of prefix increment (++i) is increment variable, return new value

Evaluation of postfix increment (i++) is increment variable, return original value

Upvotes: 2

Related Questions