Thursday, July 9, 2009

How the increment (++) operator in C works if there is two instance of the same variable?

The below program is, yes, very stupid, but this comes from my school...





#include %26lt;stdio.h%26gt;


int main(void) {





int i=4;


printf("++i=%d and i=%d\n", ++i, i);


printf("i=%d\n", i);


printf("i++=%d and i=%d\n", i++, i);


printf("i=%d\n\n", i);


return 0;





}





The output is:





++i=5 and i=4 // line 1


i=5


i++=5 and i=5


i=6





My question is, the line 1 of the output corresponds to this source line: printf("++i=%d and i=%d\n", ++i, i);


before that i is 4; how come the first print is "5" but the second print is "4".





What is the order of operations internally done after compiling it?


Does a function call in C work right-to-left?

How the increment (++) operator in C works if there is two instance of the same variable?
K%26amp;R and ISO ans ANSI C simply do not define the order of evaluation of function arguments --- it's entirely left up to the convenience of the compiler and the compiler can change it's mind about this any time it wants (honest).





I hope I'm not doing your homework for you --- if so, you are a going to grow up to be a stupid cheat.
Reply:Very interesting question! I think the answer lies in the parameter passing convention the compiler uses.





A parameter passing convention is like pass by value, pass by name, pass by result, pass by value-result, pass by reference, etc.





One of these conventions, I can't remember exactly which, will evaluate the parameters first and then send those values to the function to work on. Another convention will actually send the expression to the function and then evaluate it. I think this second situation is what is going on here.





So the compiler is compiling this into code that (virtually, not physically) passes the expression to printf, which then evaluates each one in its own scope:





++i evaluates to 5


i evaluates to 4





If you had the first convention I talked about, the instances of i in these parameters would be bound to the i in the main function, and ++i would affect the second i that is passed.





Long story short: there is no C-wide convention and it depends on your compiler.
Reply:++i increments the variable by one BEFORE it is used


i++ increments the variable by one AFTER it is used.





Cheers :-)
Reply:I read somewhere (maybe from MSDN) that the order in which parameters of a function are processed is not well-defined.





So this kind of statement:


Function_Name(i, ++i, i, ++i, i); can produce inconsistent results.

wedding florist

No comments:

Post a Comment