0

Consider the following code snippet:

#include <iostream>
using namespace std;

int main() {
    int x = 10;
    std::cout << (x++) << std::endl;
    return 0;
}

I expect the x++ to be equivalent to ++x as the expression is enclosed by round brackets. And accordingly expect 11 to be printed, but the output is 10. Why?

EDIT: I understand that pre and post increment work differently, what I don't understand is that why bracket priority is ignored i.e if I say x = (a +b) * c, I expect a and b to be added first and then multiplied with c, instead of b *c and then addition with a

Arun
  • 3,138
  • 4
  • 30
  • 41
  • 5
    *I expect the x++ to be equivalent to ++x as the expression is enclosed by round brackets.* What gives you such a strange idea? Pre and post-increment is not a matter of priority. – Frédéric Hamidi Jun 23 '16 at 06:41
  • 2
    You might have learned PEMDAS in school as "do the thing in parentheses *first*", but it's only taught like that because mathematical expressions are side-effect-free. It's really about argument grouping, and in programming, where execution order actually matters, our PEMDAS equivalents explicitly have nothing to do with execution order. – user2357112 Jun 23 '16 at 06:45
  • The post-increment gets executet at the end of the statement (after ;), not regarding the brackets in the calculation. – Spitzbueb Jun 23 '16 at 06:46
  • 2
    @Wernerson: That's not guaranteed either. – user2357112 Jun 23 '16 at 06:48

0 Answers0