Using ++ as a prefix to a statement of access through class member not causing an error

Viewed 73

I am kind of confused right now, I was running the following code:

std::vector<int> test{1, 5, 10};
++test.at(1); // I'm trying to increment that number 5 to six, which works
std::cout << test.at(1) << std::endl; // Prints out 6 to the console

I was expecting it to give me a compiler error because as I had read from about the operator precedence that the . (for member access) and the increment operator (++) have the same precedence, but they read left to right on a statement, from what I understood anyways. So in the code shown above I thought it would have been equal to saying (++test).at(1), which obviously causes a compiler error. Why isn't that the case even though the associativity is left to right, why is it reading it (from what I think) like this... ++(test.at(1))? If they have the same precedence wouldn't it, just like in maths, for example, use the ++ first and then the .?

2 Answers

True, postfix increment (a++) and member access (.) have the same precedence.

But you're using prefix increment (++a).

Consult cppreference's precedence chart.

Indeed, test++.at(i) would error for the reasons you give, though as readers of the code we would not be in any way surprised in that case.

Function calls have a higher operator precedence than unary operators like "++". The function call at() gets resolved first, and so the increment operator takes place on what it returns instead of the container.

https://en.cppreference.com/w/cpp/language/operator_precedence

EDIT: As Asteroids With Wings pointed out in their answer, only the prefix version of "++" has lower precedence than the function call. The postfix "++" is at the same level of precedence.

Related