Search code examples
cuser-defined-functionsellipsis

How to write functions with variable arguments in C


I want to write a function with variable number of arguments in c..can some one guide me..


Solution

  • Such function calls ellipses: http://www.learncpp.com/cpp-tutorial/714-ellipses-and-why-to-avoid-them/

    Because ellipses are rarely used, dangerous, and we strongly recommend avoiding their use, this section can be considered optional reading.

    If you nevertheless need such a function, take a look at this example (the point is va_list):

    double FindAverage(int nCount, ...)
    {
        long lSum = 0;
    
        // We access the ellipses through a va_list, so let's declare one
        va_list list;
    
        // We initialize the va_list using va_start.  The first parameter is
        // the list to initialize.  The second parameter is the last non-ellipse
        // parameter.
        va_start(list, nCount);
    
        // Loop nCount times
        for (int nArg=0; nArg < nCount; nArg++)
             // We use va_arg to get parameters out of our ellipses
             // The first parameter is the va_list we're using
             // The second parameter is the type of the parameter
             lSum += va_arg(list, int);
    
        // Cleanup the va_list when we're done.
        va_end(list);
    
        return static_cast<double>(lSum) / nCount;
    }