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?
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).
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With