1

I have seen lots of answer on this but i can not get the actual reason for it in some they say it work using the stack concept while in other they mention of undefined behaviors....So please let me know...what's right....My code is ...i have compiled and run this on Code block....

int i=10;
printf("\nThe initial value of i -> %d",i);
printf("\n");
printf("The value of --i-> %d and that of --i -> %d and that of i -> %d",--i,--i,i);
printf("\n");

The output i get is 8 8 8...please tell me how its being evaluated....in C.

and when i modify the above program....

i=10;
printf("\nThe initial value of i -> %d",i);
printf("\n");
printf("The value if i++ -> %d and that of --i-> %d and that of --i -> %d and that of i -> %d",i++,--i,--i,i);
printf("\n");

the output i get in this case is 8 9 9 9...so how are these thing going....and evaluated in C....please let me know

Anurag Singh
  • 727
  • 6
  • 10
  • 27

2 Answers2

2

It is a undefined behavior.

printf("The value of --i-> %d and that of --i -> %d and that of i -> %d",--i,--i,i);

i is modified more than once in the above statement.

The Standard in C++ says

Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

and

The prior value shall be accessed only to determine the value to be stored.

It means, that between two sequence points a variable must not be modified more than once and, if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written.

Balu
  • 2,247
  • 1
  • 18
  • 23
-2

Pre- decrement takes precedence over post increment. So what happens is value, at the address where i stored (say address x), gets decremented twice and becomes 8.

Now the first argument i++ gets ivaluated. As this is post increment, value is used first (so 8 is printed) and then incremented . hence, what has happened finally is value at address x is incremented by 1 and becomes 9.

Now, we have already done with pre-decrement. So printf only remembers to print the value at address of i i.e. address x that we have assumed.

And finally because of forth argument i, one more 9 is printed.

Bhavesh Munot
  • 675
  • 1
  • 6
  • 13