Thursday, October 06, 2005

When we call a function in C, some details are sent into the stack. These include the details like the address of the location in the calling function where the control must return after a call to the function and also the details pertaining to the arguments.
But there is one question remaining: What is the order in which the arguments are passed? Meaning: Are they passed from the leftmost to rightmost OR rightmost to leftmost?
The answer to this is Right to left (rightmost argument is pushed first and it continues until the leftmost argument gets pushed). In case of Pascal, it was the other way round(Left to right). Why is this difference? Is there any advantage/disadvantage of these approaches?
Well the advantage of the Left to right (Pascal) approach is that it is faster. The advantage of the Right to Left (C) approach, is that we can implement functions with variable number of arguments only in this approach.
Let us say that we have a program with a printf call as shown below:

#include
void main(void)
{
int i=20;
printf("Hello %d people", i);
}

In this case the call to printf will cause the the second argument (i) to be pushed into the stack first and then the first argument (Hello %d people) to be pushed.
When popping out the arguments, the first argument is popped out first. On scanning the first argument, printf knows how many more arguments it must look for. Thus this helps in (though is not the only criteria for) the implementation of variable number of arguments being supported for a function.