C Variable Arguments

Variable arguments in C provides flexibility to programmers to declare functions with variable arguments. Variable arguments becomes useful when the number of arguments are not known. For example, you want to merge some 3D objects like a sphere or cube and you don't know how many objects would be merged.

Variable number of arguments are represented by three dotes or ellipses (…).

Syntax

return_type function_name(int no_of_arg, ...)
{
 //code
}

Variable Arguments Sample Code

Code

#include <stdio.h>
#include <stdarg.h>

double find_volume(int,...);

int main(void) 
{
    printf("The total volume of 5 cubes of length 1 m, 2 m, 3 m, 4 m and 5 m respectively is : ");
	
    //find_volume(no_of_arg,...);
    printf("%.2lf cubic metres.\n",find_volume(5,1,2,3,4,5));
   
    return 0;
}

double find_volume(int num,...) 
{
    va_list valist;
    double sum = 0.0;
    int i,temp;
    
    // initialize valist
    va_start(valist, num);

    // access all the arguments assigned to valist
    for (i = 0; i < num; i++) 
    {
        temp = va_arg(valist, int);
        sum += temp * temp * temp;
    }
	
    // clean memory reserved for valist
    va_end(valist);

    return sum;
}

Output

The total volume of 5 cubes of length 1 m, 2 m, 3 m, 4 m and 5 m respectively is : 225.00 cubic metres.

Trending

C Programming

Remember to follow community guidelines and don't go off topic.