Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C functions support an arbitrary number of arguments?

Tags:

c

PHP has a func_get_args() for getting all function arguments, and JavaScript has the functions object.

I've written a very simple max() in C

int max(int a, int b) {
    
    if (a > b) {
        return a;   
    } else {
        return b;
    }
}

I'm pretty sure in most languages you can supply any number of arguments to their max() (or equivalent) built in. Can you do this in C?

I thought this question may have been what I wanted, but I don't think it is.

Please keep in mind I'm still learning too. :)

Many thanks.

like image 296
alex Avatar asked Nov 28 '22 19:11

alex


2 Answers

Yes, C has the concept of variadic functions, which is similar to the way printf() allows a variable number of arguments.

A maximum function would look something like this:

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

static int myMax (int quant, ...) {
    va_list vlst;
    int i;
    int num;
    int max = INT_MIN;

    va_start (vlst, quant);

    for (i = 0; i < quant; i++) {
        if (i == 0) {
            max = va_arg (vlst, int);
        } else {
            num = va_arg (vlst, int);
            if (num > max) {
                max = num;
            }
        }
    }
    va_end (vlst);
    return max;
}

int main (void) {
    printf ("Maximum is %d\n", myMax (5, 97, 5, 22, 5, 6));
    printf ("Maximum is %d\n", myMax (0));
    return 0;
}

This outputs:

Maximum is 97
Maximum is -2147483648

Note the use of the quant variable. There are generally two ways to indicate the end of your arguments, either a count up front (the 5) or a sentinel value at the back.

An example of the latter would be a list of pointers, passing NULL as the last. Since this max function needs to be able to handle the entire range of integers, a sentinel solution is not viable.

The printf function uses the former approach but slightly differently. It doesn't have a specific count, rather it uses the % fields in the format string to figure out the other arguments.

like image 39
paxdiablo Avatar answered Dec 05 '22 02:12

paxdiablo


You could write a variable-arguments function that takes the number of arguments, for example

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

int sum(int numArgs, ...)
{
    va_list args;
    va_start(args, numArgs);

    int ret = 0;

    for(unsigned int i = 0; i < numArgs; ++i)
    {
        ret += va_arg(args, int);
    }    

    va_end(args);

    return ret;
}    

int main()
{
    printf("%d\n", sum(4,  1,3,3,7)); /* prints 14 */
}

The function assumes that each variable argument is an integer (see va_arg call).

like image 123
AndiDog Avatar answered Dec 05 '22 03:12

AndiDog