Reputation: 227
I have a vague understanding of what 'C portability' means (IIRC, it means that the C language spans multiple platforms, but must adhere to certain standards (?)) and would like to know if we can portably write programs that would accept any number of arguments (even none).
What I do know is that without considering portability, all functions written with an empty pair of parentheses '()' can accept x-amount of arguments, but what about with it? It seems that there are a few papers on encouraging limitations regarding the number of arguments accepted by portably defined functions but I have yet to find one that says we cannot pass x-number of arguments (where is x is not bounded).
Upvotes: 2
Views: 3949
Reputation: 52314
a function defined with an empty set of parenthesis:
void f() {...}
accept no parameters and it is undefined behavior to call it with any.
a function declared with an empty set of parenthesis:
void g();
must be called with the same number and same type of parameters that it has been defined, but the compiler won't check it. It is an undefined behavior if you mess up.
to declate a function as taking no parameter (and thus getting an error message if you mess up), use
void g(void);
a function may be variadic, but to call it you must see a declaration which state the function is variadic:
void h(int nb, ...);
(Not that in C a variadic function must have at least one non variadic parameter, in C++ it isn't the case) A variadic function must be called with at least the non variadic argument specified.
The minimum limit on the number of parameters (for any function) is 127. (Well, what the standard says is that an implementation must be able to compile at least one program reaching that limit).
--
To clear up a confusion:
void f() { ... }
vs
void g(void) { ... }
f
is defined as accepting no parameters and can't be called with any by declared as accepting an unknow number of parameters so the compiler will not ensure that no paramaters are given. g
is defined and declared as accepting no parameters. It's a left over of K&R days with functions definitions like
int h()
int i;
{...}
which declares a function taking an indeterminate number of parameters but define it as taking one int parameter. This style is totally out of fashion and the only case of practical importance remaining is the f vs g one.
Upvotes: 4
Reputation: 108978
Use <stdarg.h>
.
See, for example, section 15, question 4 of the C-FAQ.
Edit: example of stdarg.h>
usage
#include <stdarg.h>
#include <stdio.h>
/* sum all values (no overflow checking) up to a 0 (zero) */
int sum(int v, ...) {
va_list va;
int s = v;
if (v) {
va_start(va, v);
while ((v = va_arg(va, int))) {
s += v;
}
va_end(va);
}
return s;
}
int main(void) {
printf("sum(5, 4, 6, 10) is %d\n", sum(5, 4, 6, 10, 0));
return 0;
}
Upvotes: 2