-2
#include<stdio.h>

int main()
{
int a = 10;

printf("%d %d %d",++a,a++,a--);

return 0;
}

I edited the code a bit..now the outputs are : 11 9 10 It's more complex now..

Anurag
  • 3
  • 2

3 Answers3

2

It's up to the compiler in which order he evaluates the parameters of a function call.


If the compiler goes from left to right (that would explain your output):

  • a is 10
  • prä-increment which means a is incremented (the value 11 is passed as parameter)
  • post-decrement which means a is decremented later (the the value 11 is passed as parameter)
  • post-increment which means a is incremented later (the value 10 is passed as parameter)

But if I compile this e.g. with another compiler I could get different output.

LMF
  • 463
  • 2
  • 10
1

Rewriting it as follows may make it easier to understand:

NOTE: I have made the assumption that the compiler will produce code to evaluate the parameters from left to right! This may be compiler specific.

#include<stdio.h>
int main()
{
    int a = 10;
    int param2, param3, param4;

    param2 = ++a;  // increments a to 11 and evaluates to 11
    param3 = a--;  // evaluates to current value of a then decrements a (11)
    param4 = a++;  // evaluates to current value of a then increments a (10)

    printf("%d %d %d",param2,param3,param4);

    return 0;
}
DanL
  • 1,974
  • 14
  • 13
0

The place of increment(++) and decrement(--) operator is very important. So in case of ++a the value is incremented from 10 to 11 and then printed, for a-- the current value is printed i.e. 10 and then the a is incremented to 11. Similarly in last case a++ current value 11 is printed and it is incremented to 12.

sandip patil
  • 191
  • 4