Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of arguments passed to a function that accepts a variable number of arguments?

How to count the no of arguments passed to the function in following program:

#include<stdio.h> #include<stdarg.h> void varfun(int i, ...); int main(){         varfun(1, 2, 3, 4, 5, 6);         return 0; } void varfun(int n_args, ...){         va_list ap;         int i, t;         va_start(ap, n_args);         for(i=0;t = va_arg(ap, int);i++){                printf("%d", t);         }         va_end(ap); } 

This program's output over my gcc compiler under ubuntu 10.04:

234561345138032514932134513792 

so how to find how many no. of arguments actually passed to the function?

like image 208
codeomnitrix Avatar asked Dec 12 '10 12:12

codeomnitrix


People also ask

How do you count the number of arguments in a function?

Syntax *args allow us to pass a variable number of arguments to a function. We will use len() function or method in *args in order to count the number of arguments of the function in python.

Which function accepts a variable number of arguments?

In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments.

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.


1 Answers

You can't. You have to manage for the caller to indicate the number of arguments somehow. You can:

  • Pass the number of arguments as the first variable
  • Require the last variable argument to be null, zero or whatever
  • Have the first argument describe what is expected (eg. the printf format string dictates what arguments should follow)
like image 145
Alexandre C. Avatar answered Oct 06 '22 01:10

Alexandre C.