Variadic function in C: function with variable number of arguments

Variadic function in C: so let’s say you want to add 2 numbers using you own defined function. Here is the code

But if the scenario is like you need to add three numbers, or maybe four numbers, or sometimes five numbers; will this function work for you? Definitely not! In this case, you need to design a function that can take valuable number of parameters so that you can pass 2 parameters, 3 parameters, ….. , n number of parameters. That is known as variadic function in C. Lets take a look at this code

Line 4: The function add() takes a number of arguments (a ranges from 0 to n) and returns a double. The first argument in the function call is assigned to the a. The … (three dot) means this is a variadic function.

Line 6: Declaring a double type variable sum which will be storing the sum of the numbers.

Line 7: We have declared a va_list named nums. Just think it as a special type of array. This special array nums will contain (not yet contained) all the variable number of parameters passed to the function add().

Line 8: This line will make the nums to contain all the a number of parameters. 

Line 9: We have a for loop which will run a times to access each and every parameters

Line 10: The va_arg(nums, double) returns one by one parameters (which must be double type. If the parameter is not in double type, it will return 0) for each function call. Note: you can not access like nums[i] as nums is a special type of array.

Line 10: va_end(sums) cleans up va_list sums.

Line 11: The sum is returned.

Think about one thing. Can we pass integer and floating point numbers at the same time to a variadic function? I hope you have got your answer.

I hope I have made the variadic function in C clear to you. If you have forgotten the function in C, please take a look at this post. Thank you.