Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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 .?

like image 775
Krapnix Avatar asked Nov 27 '20 21:11

Krapnix


1 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.

like image 59
Asteroids With Wings Avatar answered Oct 02 '22 14:10

Asteroids With Wings