Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading