Increment and decrease do not work in expected order

2
int main(){
  int i=5;
  printf("%d%d%d%d%d",i++,i--,++i,--i,i);
}
  

Output: 45555

Why this output? I did not understand the reason for this exit correctly.

    
asked by anonymous 12.12.2017 / 18:36

1 answer

2

There are no guarantees about the order of execution of the arguments in the function call, so the intuition indicates that it will do this order and the result would be "56655", but each compiler can do as it sees fit. This is considered a undefined behavior . If you want to order one by statement , do not use it as expressions using the list operator (comma).

Remember that the ++ and -- operators are assignors, so they produce side effects by changing the value of the variable. If the intention is to add or subtract 1 from the value of the variable without changing the value of itself, then it has to use an operator that does not assign, that does not generate collateral effect. In this case it would be i + 1 or i - 1 , so it would generate the result and use it without affecting the variable. In this case the result would be "64645". Of course it would be semantically very different from what you posted, you do not seem to want to know this.

This works as expected:

#include <stdio.h>

int main() {
    int i = 5;
    printf("%d", i++);
    printf("%d", i--);
    printf("%d", ++i);
    printf("%d", --i);
    printf("%d", i);
}

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

    
12.12.2017 / 18:43