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 .
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With