-3

I declared a variable suppose i = 1 And then I used unary decrement operator in printf function

printf("%d %d",i--,i);

I expected the output to be 1 0 but the output displayed was 1 1 Why the value of i is not getting decremented?

Amit
  • 13,134
  • 17
  • 77
  • 148
  • 1
    Probably because *in your environment* that *specific compiler* decided to evaluate parameters from the last one to the left. Anyway AFAIR the sequence point is after the function call, so there is no guarantee as to *when* the result of postdecrement result appears, until the return from `printf()`. – CiaPan May 26 '15 at 07:50
  • I just tested this and my output is `1 0` – moffeltje May 26 '15 at 07:50
  • @CiaPan there is no guarantee of anything when undefined behaviour happens – M.M May 26 '15 at 08:14
  • @MattMcNabb Yes, in this particular code there's UB and no guarantee at all. But if there was `fun(i--,j++);` it would not be UB but you still couldn't tell when the modified values are actually stored, until after the return from `fun()` (and it's still implementation-defined which one would be stored first). – CiaPan May 26 '15 at 08:41
  • @CiaPan But in that case the output would be well-defined – M.M May 26 '15 at 08:46

2 Answers2

3

The order of evaluation of function parameters is not guaranteed in C. It might be left to right, or it might be right to left. It's up to the compiler implementation.

It is undefined behaviour to have multiple references to a variable in combination with increment or decrement operators in one expression.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
-1

i-- decrements the value after being evaluated.

post-increment and post-decrement creates a copy of the object, increments or decrements the value of the object and returns the copy from before the increment or decrement. http://en.cppreference.com/w/cpp/language/operator_incdec

Furthermore, the order of evalation is not guaranteed. So i (the second argument) could be evaluated before i-- (the first one)

Atmocreations
  • 9,923
  • 15
  • 67
  • 102
  • (a) `i--` does not increment the value at all; (b) The side-effect of `i--` is not sequenced-after the value computation. The compiler could choose to decrement the value first, and then evaluate `i + 1`; (c) You linked a C++ reference but this is a C question. The increment operators have different sequencing in C than in C++. (d) As well as order of evaluation not being guaranteed, the behaviour of the whole program from this point (and backwards in time also in some cases) is undefined. – M.M May 26 '15 at 08:19
  • Thanks for pointing out. a) I corrected my typing mistake. – Atmocreations May 26 '15 at 12:36