How can a function accepts variable mumber of arguments in C ?

 Posted by Nithadeepak on 5/2/2011 | Category: Others Interview questions | Views: 2669 | Points: 40

Functions accepting variable number or type of arguments in C
A function to take variable number or type of arguments are referred to as varargs functions or variadic functions.

You can define a function as variadic using ellipsis('...') in the argument list. To access their variable arguments, you have to use special macros.

The only way to access them is sequentially, in the order they were written,using the special macros from stdarg.h in the following 3 steps:

•Initialize an argument pointer variable of type va-list using va-start.The argument pointer when initialized points to the first optional argument.

•Access optional argument by successive calls to va-arg. The first call to va-arg gives 1st optional argument, the next call gives you the second and so on.

•You indicate that you are finished with the argument pointer variables by calling va-end.

A macro is a fragment of code which has been given a name-whenever the name is used,it is replaced by the content of the macro.

Data Type: va-list
The type va-list is used for argument pointer variables.

Macro: va-start(va-list ap,last-required)
This macro initializes the argument pointer variable ap to point to the first of the optional argument of the current function.
last-required must be the last required argument of the function.

Macro: type va-arg(va-list ap,type)
The va-arg macro returns the value of the next optional argument, and modifies the value of ap to point to the subsequent argument. Thus successive use of va-arg returns successive optional argument.
The type of the value returned by va-arg is the type specified in the call.

Macro: void va-end(va-list ap)
This ends the use of ap. After the va-end call, further va-arg calls with the same ap may not work.



int add-em-up(int count,...)
va-list ap;
int i,sum;
return sum;

void main()

printf("%d",add-em-up(3,5,5,6)); /* prints 16 */
printf("%d",add-em-up(10,1,2,3,4,5,6,7,8,9,10)); /*prints 55 */

Source: | | Alert Moderator 

Comments or Responses

Login to post response

More Interview Questions by Nithadeepak