C function with optional arguments - the best way? -
this question has answer here:
- an example of use of varargs in c 4 answers
is there way in c have function take optional arguments? if not how syscalls work argument list variable?
if want function takes optional arguments, need use stdarg family of functions.
for example, suppose have function takes 2 int arguments , 1 or more optional int arguments. write follows:
void myfunc(int x, int y, ...) { va_list args; int i; printf("x=%d, y=%d\n", x, y); // y indicates how many optional arguments if (y > 0) { // initialize reading of optional args, passing in last explicit argument va_start(args, y); (i=0; i<y; i++) { // read optional int arg int z = va_arg(args, int); printf("z[%d]=%d\n", i, z); } // done reading optional args va_end(args); } } you need have @ least 1 explicitly named argument, , have have way of knowing how many optional arguments there are. in example, argument y indicates how many optional arguments there are.
let's @ system function, open. man page shows following prototypes:
int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); in c, can't have 2 functions same name. if in header files, you'll find this:
int open(const char *pathname, int flags, ...); in case, if flags argument has o_creat flag set, knows read single optional argument.
then there's execl function:
int execl(const char *path, const char *arg, ...); this function takes arg first argument of program run, reads optional arguments, each of char *, read subsequent arguments. caller expected pass null last argument indicate end of argument list. when function reads optional arguments, knows it's done when reads null pointer.
Comments
Post a Comment