Increment/Decrement Operator

Programming in C:
I have run the following code:

int I = 5;
printf("%d,%d,%d",I++,I,++I);

The output I expected was 667.After running this code it was 677.
Could anyone explain this?

You can see some explanation here itself…

thanks sir

Before asking these type of Q, atleast google first. Its one of the most basic question of this operator.

1 Like

yes it is sir. But, look carefully please. I have already used associativity and stack concept of storing by printf and later printing in lifo order. Couldn’t find any explanation for this error. plz help:)

Good.You ought to tell what you did, and how is it being a problem. If you dont tell about your attempt, then it will be seen as you didnt even bother to search/google it.

In C, C++, you should always tend to avoid multiple increments in a single line. The reason is told by your IDE-

C:\project\sasa\main.cpp|29|warning: operation on 'l' may be undefined [-Wsequence-point]|
C:\project\sasa\main.cpp|29|warning: operation on 'l' may be undefined [-Wsequence-point]|
C:\project\sasa\main.cpp|29|warning: operation on 'l' may be undefined [-Wsequence-point]|
C:\project\sasa\main.cpp|29|warning: operation on 'l' may be undefined [-Wsequence-point]|

If you try printing printf("%d %d %d %d %d",l++,l,++l,l++,++l); then it prints 8 9 9 6 9 for l=5 . How will you explain the second last 6?

Multiple increments using “++” in a single line must be avoided. I still remember my professor saying that this gives undefined behavior, you cannot predict what it can print until you see whats printed.

noted sir.

ohkay sir. thanks for suggestion.