How to pass any number of arguments to user definition functions in C?

How to pass any number of arguments to user definition functions in C? What is the prototype of this feature? It is similar to printf, which can take any number of arguments.

+4
source share
2 answers

Look here for an example.

#include <stdlib.h> #include <stdarg.h> #include <stdio.h> int maxof(int, ...) ; void f(void); main(){ f(); exit(EXIT SUCCESS); } int maxof(int n args, ...){ register int i; int max, a; va_list ap; va_start(ap, n args); max = va_arg(ap, int); for(i = 2; i <= n_args; i++) { if((a = va_arg(ap, int)) > max) max = a; } va_end(ap); return max; } void f(void) { int i = 5; int j[256]; j[42] = 24; printf("%d\n",maxof(3, i, j[42], 0)); } 
+7
source

Such a function is variable, but such functions are much less useful than they might seem at first glance. The wikipedia page on this topic is not bad and has a C code.

The main problem with such functions is that the number of parameters cannot actually be variable - they must be fixed at compile time by a known parameter. This is obvious in printf:

printf ("% s% d", "Value is", 42);

The number of% specifiers must correspond to the number of actual values, and this is true for all other applications of variational functions in C in one form or another.

0
source

All Articles