C Variable Arguments

C Variable Arguments


Lets take look at below example code –

1

2

3

4

5

6

7

8

9

10

11

12

int sum(int, ... )

{

   .

   .

   .

}

 

int main()

{

   sum(1, 2, 3);

   sum(1, 2, 3, 4);

}

In C Programming Language we can define a function with variable number of arguments. This can be achieved using three special macros va_start, va_arg & va_end are defined in stdarg.h, to process the variable arguments.

In order to access the variable argument list va_start must be called as below –

1

void va_start(va_list pvar, void pname);

va_start() is used to initialize pvar to the beginning of the variable argument list. va_start() must be invoked before any access to the unnamed arguments. The parameter ‘pname’ is the identifier of the rightmost parameter in the variable parameter list in the function definition (the one just before the ellipses ie., “, …”).

After the initialization we can access the variable argument list via va_arg macro.

1

(type *) va_arg(va_list pvar, type);

pvar is a pointer to variable argument list; and type is the type name of the next argument to be returned.

 

va_arg() expands to an expression that has the type and value of the next argument in the call. The parameter pvar must be initialized by va_start().Each call to this macro will extract the next argument from the argument list as a value of the specified type.

When all the arguments have been processed, the va_end function should be called. This will prevent the va_list supplied from being used any further. The va_end function is declared as

1

void va_end(va_list pvar);

pvar is a pointer to variable argument list

The va_end() macro is used to clean up.If va_end is not used, the behaviour is undefined.The entire argument list can be re-traversed by calling va_start again, after calling va_end.

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

#include<stdio.h>

#include<stdarg.h>

void hello(char *msg, ...);

 

int main()

{

    hello("counter",1,5,10,15);

    return 0;

}

void hello(char *msg, ...)

{

    va_list ptr;

    int num;

    va_start(ptr, msg);

    num = va_arg(ptr, int);

    num = va_arg(ptr, int);

    printf("counter is %d", num);

}

 

Output:

counter is 5

 

POST NAVIGATION

 In this tutorial we have learn about the C Variable Arguments and its application with practical example. I hope you will like this tutorial.


 

 

 

Copyright © 2022 W3Adda. All Rights Reserved.

  •  
  •  
  •