Click here to Skip to main content
15,900,378 members
Please Sign up or sign in to vote.
2.00/5 (3 votes)
See more:
#include<stdio.h>
#include<conio.h>

int f1();
int f2();
void main()
{
clrscr();
 printf(" %dt %d", f1(), f2());
  getch();
}
int f1()
{
 printf("f1() enteredn ");
 return 4;
}

int f2()
{
 printf("  f2() enteredn ");
 return 5;
}</conio.h></stdio.h>



Out put:
f2() enteredn f1() enterdn 4t 5

Why the output is as like that, why not as fi() enterdn 4t f2() enterdn 5 Than how printf Function is simulated here ?
Posted

This has to do with the way the compiler generates the code that evaluates the parameter lists of a function. You have just found out that the parameter list of your printf call in main is evaluated from right to left.

That's all there is to it.

Cheers,
 
Share this answer
 
v3
Comments
Wendelius 29-Mar-11 15:23pm    
Good answer, my 5. Just a note: is the ordering vice versa :)
Manfred Rudolf Bihy 29-Mar-11 15:28pm    
Thanks, I'll fix that! :)
Sergey Alexandrovich Kryukov 29-Mar-11 15:38pm    
Correct, my 5.
--SA
The C standard (and the C++ specification) does not impose any restrictions on the roder in which function parameters are evaluated. As a result it is implementation specific, and can change from compiler to compiler. If you think about it, there is some sense in evaluation from the RHS, since the resulting values can be pushed onto the stack in reverse order so the LHS parameter is always at the top - simpler to code when you enter the routine if that is the case.

So, printf parameters can be worked out in any order the compiler wants. Do not rely on this behaviour: there is absolutely no guarantee that the next service pack will not change it! (Having said that, it probably won't, but really, really, do not do it!)
 
Share this answer
 
Comments
Wendelius 29-Mar-11 15:25pm    
Good note, my 5
Manfred Rudolf Bihy 29-Mar-11 15:29pm    
Good point stressing the implementation dependancy! 5+
Because f2 is called first (this leads to "f2() enteredn "), then f1 (now you have "f2() enteredn f1() enteredn") and in the end the last output is appended which is your numeric values. So the calls are done in reverse order.
 
Share this answer
 
Comments
Manfred Rudolf Bihy 29-Mar-11 15:21pm    
Now that was easy, wasn't it? :)
My 5!
Wendelius 29-Mar-11 15:31pm    
Thanks.
UL UL ALBAB 29-Mar-11 15:32pm    
Thanks... Your answer is really great.
Sergey Alexandrovich Kryukov 29-Mar-11 15:38pm    
Sure, my 5.
--SA
Wendelius 29-Mar-11 15:45pm    
Thanks :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900