-2

My question is inspired from the below code

int a=4;

    int d=(++a) + (++a);  // stored value 12

    a=4;

    int e=++a + a++;  //Actual stored value  11
    a=4;

    int f=a++ + a++;  //Actual stored value 9
    a=4;

    int g=a++ + ++a;  //Actual stored value 10

I have seen that the precedence of postfix operator is more than prefix operator . Hence ,

   'd' in my opinion should be (5+6)
   'e' in my opinion should be (6+4)
   'f' in my opinion should be (4+5)
   'g' in my opinion should be (4+6)

I am using gcc 7.4.0

Can anyone please help with how to reason the non-matching results ?

NOTE: The variables in which the expression(d,e,f,g) is being stored is not the same as the variable involved in expression(a).

Excalibur
  • 29
  • 1
  • 6
  • Exactly. All of the above is undefined behavior, as the components of the expression can be executed in any order. – anonmess Sep 23 '19 at 17:55
  • @anonmess But aren't the precedence and associativity rules meant to deal with such stuff ? – Excalibur Sep 23 '19 at 17:57
  • 1
    The precedence and associativity rules describe how a statement is interpreted, but not how it is evaluated. The C standard explicitly says that what you're doing leads to undefined behaviour. See the duplicate. – Jonathan Leffler Sep 23 '19 at 18:00
  • @Excalibur If you think carefully about how precedence and associativity are defined, they don't and can't answer the question of precisely how an expression like `a++ + a++` would be evaluated. You'd need additional rules (like Java, for example, has, but C does not) to make these expressions well-defined. Also, note that the parentheses in `(++a) + (++a)` accomplish nothing -- see the second dup. – Steve Summit Sep 23 '19 at 18:38

1 Answers1

-1

According to the C language standard, you are using "undefined behavior" as the order of operation for the evaluation of the items in parentheses is not guaranteed. So the code for your int d=(++a) + (++a); can do both increments first, making a==6 then do the sum, yielding d==12.

This is why you shouldn't use such code structures and they only appear in school assignments.

daShier
  • 2,056
  • 2
  • 8
  • 14
  • Not my downvote, but you shouldn't really answer these questions that have good answers elsewhere. The two questions that this question is listed as duplicate of are the main ones for prefix and postfix increment. – S.S. Anne Sep 23 '19 at 19:13
  • 1
    @JL2210 Point taken. Thanks. – daShier Sep 23 '19 at 19:14