Operation sequence

14 Views Asked by At

I am new to programming and wanted to understand more on operator associativity and precedence.

#include <iostream>

using namespace std; int main() {

int a=5;
cout << a + a++ + 1 ;
return 0;

}

For the above prog , the output returned is 12

Question 1)

a++ is evaluated first, followed by a and 1 , i.e; a++ + a + 1 as per precedence which becomes 5 + 6 + 1 = 12 , is this correct ??

Question 2)

But, when I write like this;

#include <iostream>

using namespace std; int main() {

int a=5;
cout << (a) + a++ + 1 ;
return 0;

}

the answer is still 12 ( brackets should override precedence) I expected the output to be : 5 + 5 + 1 = 11

Would like to know the sequence of steps here.

0

There are 0 best solutions below