Increment and decrement do not work in expected order

Asked

Viewed 58 times

2

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

output: 45555

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

  • To get the output with increments and prompts you have to take sequential steps

  • The problem is that as @Maniero said in the answer below there is no order guaranteed, but also another problem is that you are doing assignment on this variable, the correct thing would be to do + 1 and - 1 to have the result without modifying the value of the variable, but without knowing the use of that instruction, one cannot be sure. I imagine this is just a case study.

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 in this order and the result would be "56655", but each compiler can do as it sees fit. This operation is considered to be a undefined behavior. If you want order do one for statement, do not use as expressions using the list operator (comma).

Remember that the operators ++ and -- are assignors, therefore 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 itself, then you have to use an operator that does not assign, that does not generate side effect. In 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 don’t seem to want to know this.

So it 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.