0

hi, i a m jigar thakkar
please help me.

int a=1;
printf("%d%d%d",a++,a++,a++);
output : 3,2,1

how work this in c?
please explain in detail?

Thanx in advance.

4
Contributors
5
Replies
6
Views
9 Years
Discussion Span
Last Post by Ancient Dragon
0

Hi, inteligent people,
i m jgiar thakkar
please help me on this :

int a=1;
printf("%d%d%d",a++,a++,a++);
output : 3,2,1

Please help how work this actually>?
Explain reason in detail.

Thanx in advance

1

Best answer is, don't do that.

You are playing with undefined behavior. For any single variable, there should be a maximum of one pre/post increment/decrement operator. Otherwise your results may vary: You could just as easily have gotten 1 2 3, 1 3 2, 3 1 2, 2 1 3, or 2 3 1.

The actual reason you are getting 3 2 1 is because your compiler plays with the arguments in the same order they must be pushed onto the stack to call a c-function. However, that's just one compiler. Others could easily give you different results. (Heck, the same compiler could give you different results at different times.)

Therefore, better to say:

int a = 1;
printf( "%d%d%d", a, a+1, a+2 );
a += 3;

This avoids the undefined behavior of multiple pre/post inc/dec ops for a single variable in one statement.

Hope this helps.

Votes + Comments
Good answer
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.