Which expression has priority in `v[–i] = 100;`? the subscripting or the unary expression

This is more of a fundamental question rather than a useful one but here it goes.

According to the C++ standard, postfix expressions (e.g., v[i]), have priority over unary expressions (e.g., --i). Therefore, I was wondering what is the actual sequence of steps that a program follows to implement this statement v[--i] = 100;.

std::vector<int> v = {0, 200};
int i = 1;
v[--i] = 100; // {100, 200}

Given the aforementioned priorities, does the program first access the element 200 of the vector, and only then the decrement happens, pointing to 0 before changing it to 100?

>Solution :

operator [] has higher precedence than operator --, but that doesn’t matter here because operator[] needs to evaluate the parameter which is --i which means --i is resolved and then it’s value is passed along to operator[]

Operator precedence is not the same as the order of operations . Operator precedence only determines which operators are applied to which expressions.

Leave a Reply