How can I create a function with extra arguments in C?

Recently I had a question when writing a program to open a file.

Let me explain my question clearly. Here I take the challenge to open as an example.

To create a file:

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

To open a file:

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

Then I clearly noticed this point, and it also works for main() .

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

So how can we create these optional arguments? How exactly can the compiler test these prototypes? If possible, write an example program.

+6
source share
2 answers

The open function is declared as a variational function. It will look something like 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); } 

Further arguments are not expended unless you indicate that they really exist.

The same construction is used for printf .

This is not always made explicit in the manual, since the only two possible signatures are (char const *, int) and (char const *, int, int) , so it makes little sense to show that you are actually accepting variable arguments. (You can verify this by trying to compile something like open("", 1, 2, 3, 4, 5, 6) .)

+7
source

In all cases, the varargs function must somehow determine from the fixed arguments the number of variables. For example, the printf() family of functions uses a format string to determine the number and type of arguments. The execl() function uses a pointer (null pointer) to indicate the end of the argument list. It would be possible to use an account instead of a sentry (but if you do, there is a chance that the counter and array in a function other than varargs will work, and if not better than count and the argument list). The open() function uses one of the flag bits to determine if mode should be present - see Kerrek SB answer .

The function main() is a special case. An implementation (compiler) is prohibited from declaring a prototype for it and must take at least two forms:

 int main(int argc, char **argv); int main(void); 

or their equivalents. It can take other forms; see Using a third environment variable in C main() ? for one general form. In C, but not C ++, the standard compiler can document other types of return data - and Microsoft has documented void as a valid return type from VS 2008 onwards.

Since the prototype main() absent during implementation, the compiler cannot officially reject any declarations / definitions of main() , although it can pass a comment on forms that it does not recognize (GCC makes a comment on main() that does not return an int type, for example )

+1
source

Source: https://habr.com/ru/post/955356/


All Articles