Question

In Python, I'm used to things like

def send_command(command, modifier = None):

and then the modifier argument is optional, and the absence of the argument can be differentiated from an argument of 0. Is there similar functionality in C? I'm inexperienced with C, and Googling, but can't find a clear statement of how to use optional parameters in C. It seems you can assign them similarly, like this:

void send_command(uint8_t command, uint8_t modifier = 0) {

so the second argument is optional and defaults to 0 if not used? (Edit: No, this is invalid C anyway)

But can the function distinguish between send_command(SOMETHING) and send_command(SOMETHING, 0)? Ideally, the second parameter could be any uint8 value, including 0.

Maybe NULL is different from 0?

void send_command(uint8_t command, uint8_t modifier = NULL) {
Was it helpful?

Solution

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

OTHER TIPS

Optional parameters are possible in C99 with variadic macros:

#define JUST3(a, b, c, ...) (a), (b), (c)
#define FUNC(...) func(JUST3(__VA_ARGS__, 0, 0))

Now FUNC(x) expands to func((x), (0), (0)), FUNC(x,y) expands to func((x), (y), (0)), etc.

As others have said, C does not have optional parameters.

As for the difference between NULL and 0, there isn't much of one.

As others said C doesn't support default arguments of functions directly. But there are ways to do this with macros. P99 has convenient "meta"-macros that make this feature relatively easy to specify. As an example to avoid to repeatedly have to specify the second argument of the pthread_mutex_init function:

P99_PROTOTYPE(int, pthread_mutex_init, pthread_mutex_t*, pthread_mutexattr_t const*);
#define pthread_mutex_init(...) P99_CALL_DEFARG(pthread_mutex_init, 2, __VA_ARGS__)
P99_DECLARE_DEFARG(pthread_mutex_init, , (pthread_mutexattr_t*)0);

and straight forward to use afterwards

pthread_mutex_init(&my_mutex);

The semantic of evaluation of the default argument here is the same as for C++, that is the evaluation context of the default argument is the context of the declaration. There is also the possibility to specify this in a way that the context of evaluation is the context of the macro invocation.

The C Programming Language has no optional parameters. C++ does, but "the mother of many modern programming languages" C does not...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top