Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

function

gcc

gnu

Recently I got a question when writing a program for file opening.

Let me explain my question clearly. Here I'm taking open call 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 observed this point and it also works for main() too.

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

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

like image 772
gangadhars Avatar asked Oct 06 '13 18:10

gangadhars


People also ask

How do you make an optional argument a function?

You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement. There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.

Can you have optional parameters in C?

C does not support optional parameters. Nor does it support function overloading which can often be used to similar effect.

What is optional in C function declaration?

The optional declaration-specifiers and mandatory declarator together specify the function's return type and name. The declarator is a combination of the identifier that names the function and the parentheses following the function name.

What is the optional value function?

By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.


1 Answers

The open function is declared as a variadic 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);
}

The further arguments are not consumed unless you have indicated that they do in fact exist.

The same construction is used for printf.

The manual doesn't always make this explicit, since the only possible two signatures are (char const *, int) and (char const *, int, int), so there's little point in revealing that you the function actually accepts variable arguments. (You can test this by trying to compile something like open("", 1, 2, 3, 4, 5, 6).)

like image 125
Kerrek SB Avatar answered Nov 15 '22 00:11

Kerrek SB