How can I make a function with optional arguments in C? -


recently got question when writing program file opening.

let me explain question clearly. here i'm taking open call example.

to create file:

open("file_name", o_creat, 0766); //passing 3 parametrs 

to open file:

open("file_name", o_rdwr); //only 2 arguments. 

then observed point , works main() too.

main(void) //worked main(int argc, char **argv); //worked main(int argc) //worked , it's doesn't give error "too few arguments".  main() //worked  

so how can create these optional arguments? how can compiler validate these prototypes? if possible, please write example program.

the open function declared variadic function. this:

#include <stdarg.h>  int open(char const * filename, int flags, ...) {     va_list ap;     va_start(ap, flags);      if (flags & o_creat)     {         int mode = va_arg(ap, int);         // ...     }      // ...      va_end(ap); } 

the further arguments not consumed unless have indicated in fact exist.

the same construction used printf.

the manual doesn't make explicit, since possible 2 signatures (char const *, int) , (char const *, int, int), there's little point in revealing function accepts variable arguments. (you can test trying compile open("", 1, 2, 3, 4, 5, 6).)


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

debian - 500 Error upon login into Plesk Admin - auth.php3? -