Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing variable number of arguments

Can we pass variable number of arguments to a function in c?

like image 770
Shweta Avatar asked Oct 01 '10 03:10

Shweta


People also ask

Can we pass a variable number of arguments to a function?

When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.

What is a variable number of arguments?

Variable length argument is a feature that allows a function to receive any number of arguments. There are situations where we want a function to handle variable number of arguments according to requirement.

How do you pass variable number of arguments to a function in Python?

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.

How many arguments can be passed?

Any number of arguments can be passed to a function. There is no limit on this. Function arguments are stored in stack memory rather than heap memory.


2 Answers

Here is an example:

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

int maxof(int, ...) ;
void f(void);

int main(void){
        f();
        exit(EXIT SUCCESS);
}

int maxof(int n_args, ...){
        register int i;
        int max, a;
        va_list ap;

        va_start(ap, n_args);
        max = va_arg(ap, int);
        for(i = 2; i <= n_args; i++) {
                if((a = va_arg(ap, int)) > max)
                        max = a;
        }

        va_end(ap);
        return max;
}

void f(void) {
        int i = 5;
        int j[256];
        j[42] = 24;
        printf("%d\n", maxof(3, i, j[42], 0));
}
like image 76
Preet Sangha Avatar answered Oct 18 '22 13:10

Preet Sangha


If it is a function that accepts a variable number of arguments, yes.

like image 39
James McNellis Avatar answered Oct 18 '22 15:10

James McNellis