-1

I'm learning CPP and I came through this piece of code.

#include <iostream>
using namespace std;
 
int main() {
 
    int a=1;
      cout<< ++a + a++ ;
}

When I run this the answer is 5.

I looked through the operator precedence and found that postfix has higher precedence than prefix. So according to me first the postfix should be evaluated after that the prefix. a++ will just substitute 1 and increment a after that , then ++a will increment a and place 3 there which should result in 4. Where am I going wrong.

mch
  • 9,424
  • 2
  • 28
  • 42
  • The semantics of that specific example changed in the C++20 standard, or was it already in C++17? Anyway, before that it was *undefined behavior*. Now it's [sequencing](https://en.cppreference.com/w/cpp/language/eval_order) being well-defined. The precedence is unrelated to the issue, it's all about sequencing. – Some programmer dude Aug 11 '23 at 07:43
  • precedence is about `++a++`. When side effects of subexpressions like eg `expr1 OP expr2` take place is not about precedence of operators – 463035818_is_not_an_ai Aug 11 '23 at 08:03

0 Answers0