Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Since a beginner i am not able to f

Status
Not open for further replies.

mad411

Technical User
Apr 4, 2002
17
IN
Since a beginner i am not able to find the logic
of this prg.
According to me the output should be :
0, -1

#include<stdio.h>
void main(void)
{
int i=-1;
printf(&quot;%d, %d&quot;,++i,i++);
}

output:
1, -1

So please explain me the logic of the same.
 
i starts off as -1.

Apparently, the arguments of printf are evaluated in reverse order (i++, then ++i), so:

i++ is a postincrement, so it evaluates to i (or -1) before it increments i, making it 0, so the second thing that gets printed is -1.

++i is a preincrement, so it first increments i, making it 1, then evaluates to i, making it 1, which is the first thing printed out.

From this, you can probably tell that, in general, it's not a good idea to use i++ and ++i in a complex operation where you need i more than once because it can be difficult to predict the order it will be evaluated in.
 
What you did was invoking an undefined behavior - actually two here:
1. 'i' is being modifying twice within a sequence point.

Both pre- and post operator have side effects on the variable ¡V the value is being incremented or decremented and yield the result before or after the changes. What is not clear is the implication of ¡§before¡¨ or ¡§after¡¨. The standard only guaranteed that the side effects are settled before the beginning of the next sequence point. Other than that, the compiler can implement anything it deems appropriate.


2. The order of argument evaluation in a function call is implementation specific.

The function call itself has two sequence points. One just after evaluating all function argument and one before the function returns. Therefore there is again no guaranty the order of evaluation of the function arguments. It can be from left to right, right to left or any order the compiler/optimizer deems appropriate.

Once an undefined behavior is invoked, the entire statement becomes undefined. There is no way to justify the results. The best deduction you can reason is how the codes are being generated by the compiler. And this cannot be guarantied to be consistent ¡V The same compiler can generate totally different codes (and thus a different result) if different compiler options (like optimization) being used.

In other words, don¡¦t do this.

Shyan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top