Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of parameters in C variable argument method call

When using va_start(), va_arg() and va_end() to read parameters passed to a method, is there a way to count how many arguments there are?

According to the man page if you call va_arg() too many times you get "random errors":

If there is no next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), random errors will occur.

like image 467
corydoras Avatar asked Oct 05 '10 22:10

corydoras


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.

How do you find the variable number of arguments?

Syntax of VarargsA variable-length argument is specified by three periods or dots(…). This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is implicitly declared as an array of type int[].

What is argument count in C?

argc (ARGument Count) is int and stores number of command-line arguments passed by the user including the name of the program. So if we pass a value to a program, value of argc would be 2 (one for argument and one for program name) The value of argc should be non negative.


1 Answers

No. a Variable Argument function (such as printf), must "know" when to stop looking for more arguments.

printf knows by the number of %d, %s and other symbols in its format string.

Other functions sometimes use Sentinel values:

sumValues(1, 3, 5, 7, 6, 9, -1); // will add numbers until it encounters a -1

Other functions may have the number of parameters stated up front:

AddNames(4, "Bill", "Alice", "Mike", "Tom");
like image 171
abelenky Avatar answered Oct 21 '22 17:10

abelenky