Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why variadic functions require at least two arguments?

I'm trying to plug a hole in my knowledge. Why variadic functions require at least two arguments? Mostly from C's main function having argc as argument count and then argv as array of arrays of chars? Also Objective-C's Cocoa has NSString methods that require format as first argument and afterwards an array of arguments ([NSString stringWithFormat:@"%@", foo]). Why is it impossible to create a variadic function accepting only a list of arguments?

like image 448
Eimantas Avatar asked Oct 02 '11 08:10

Eimantas


2 Answers

argc/argv stuff is not really variadic.

Variadic functions (such as printf()) use arguments put on the stack, and don't require at least 2 arguments, but 1.

You have void foo(char const * fmt, ...) and usually fmt gives a clue about the number of arguments. That's minimum 1 argument (fmt).

like image 100
cJ Zougloub Avatar answered Sep 28 '22 18:09

cJ Zougloub


C has very limited reflection abilities so you must have some way to indicate what it is that the variable arguments contain - either specifying the number of arguments or the type of them (or both), and that is the logic behind having one more parameter. It is required by the ISO C standard so you can't omit it. If feel you don't need any extra parameters because the number and type of the arguments is always constant then there is no need for variable arguments in the first place.

You could of course design other ways to encode the number / type information inside the variable arguments such as a sentinel value. If you want to do this, you can just supply a dummy value for the first argument and not use it in the method body.

And just to be pedantic about your title, variadic functions only require one argument (not two). It's perfectly valid to make a call to a variadic function without providing any optional arguments:

printf("Hello world");
like image 31
Mark Byers Avatar answered Sep 28 '22 19:09

Mark Byers