C default arguments
Asked Answered
J

24

367

Is there a way to specify default arguments to a function in C?

Jerricajerrie answered 24/9, 2009 at 14:38 Comment(4)
just want a slightly better C, not C++. think C+ . with a variety of small improvements lifted from C++, but not the big mess. And, please, no different link-loader. should be just another preprocessor-like step. standardized. everywhere...White
Related question that I didn't see listed in the side bar.Porch
I'd say stop being a barbarian and learn to use C++(11, ...) well - jk! /me puts out flames... but... you will come to love it... hahaha i can't help myself, sorry.Kasten
Possible duplicate of Default values on arguments in C functions and function overloading in CUnconnected
A
171

Not really. The only way would be to write a varargs function and manually fill in default values for arguments which the caller doesn't pass.

Aberration answered 24/9, 2009 at 14:40 Comment(10)
I hate the lack of checking when using varargs.Striction
As well you should; I actually don't recommend this; I just wanted to convey that it is possible.Aberration
However, how do you wanna check whether the caller passes the argument or not? I think for this to work, don't you have the caller to tell you that he didn't pass it? I think this makes the whole approach somewhat less usable - the caller could aswell call a function with another name.Hujsak
That is definitely the problem, since there's no reliable, cross-platform way to check whether anything was passed at all or how many arguments they sent you. So varargs might work well if you have a function where it makes sense to call it like f(5, 6, 7, NULL) with some kind of terminating argument. I do occasionally write functions for which this might make sense, though not often, which is why I started my answer by saying, "Not really."Aberration
The open(2) system call uses this for an optional argument that may be present depending on the required arguments, and printf(3) reads a format string that specifies how many arguments there will be. Both use varargs quite safely and effectively, and though you can certainly screw them up, printf() especially seems to be quite popular.Akiko
Printf is actually a bad example because C compilers actually end up checking the number of arguments you pass to printf and giving you errors if you pass the wrong number. The varargs function itself is not able to do that, since there's no function or macro to tell you how many parameters were actually passed.Aberration
@Eli: Not all C compilers are gcc. There's some advanced compiler magic going on for it to warn when your printf() args don't match your format string. And I don't think it's possible to get similar warnings for your own variadic functions (unless they use the same style of format string).Ediva
@BenjaminGruenbaum: Good catch, I've updated the link to point to Wikipedia.Aberration
does anyone have an implementation of this? even if it's BAD idea.Fruiterer
How is it possible that there are two open() functions with the same name? int open(const char *pathname, int flags) and int open(const char *pathname, int flags, mode_t mode); (see man 2 open)Genny
A
368

Wow, everybody is such a pessimist around here. The answer is yes.

It ain't trivial: by the end, we'll have the core function, a supporting struct, a wrapper function, and a macro around the wrapper function. In my work I have a set of macros to automate all this; once you understand the flow it'll be easy for you to do the same.

I've written this up elsewhere, so here's a detailed external link to supplement the summary here: http://modelingwithdata.org/arch/00000022.htm

We'd like to turn

double f(int i, double x)

into a function that takes defaults (i=8, x=3.14). Define a companion struct:

typedef struct {
    int i;
    double x;
} f_args;

Rename your function f_base, and define a wrapper function that sets defaults and calls the base:

double var_f(f_args in){
    int i_out = in.i ? in.i : 8;
    double x_out = in.x ? in.x : 3.14;
    return f_base(i_out, x_out);
}

Now add a macro, using C's variadic macros. This way users don't have to know they're actually populating a f_args struct and think they're doing the usual:

#define f(...) var_f((f_args){__VA_ARGS__});

OK, now all of the following would work:

f(3, 8);      //i=3, x=8
f(.i=1, 2.3); //i=1, x=2.3
f(2);         //i=2, x=3.14
f(.x=9.2);    //i=8, x=9.2

Check the rules on how compound initializers set defaults for the exact rules.

One thing that won't work: f(0), because we can't distinguish between a missing value and zero. In my experience, this is something to watch out for, but can be taken care of as the need arises---half the time your default really is zero.

I went through the trouble of writing this up because I think named arguments and defaults really do make coding in C easier and even more fun. And C is awesome for being so simple and still having enough there to make all this possible.

Aulic answered 28/5, 2010 at 1:39 Comment(14)
+1 creative! It has its limitations but also brings named parameters to the table. Note that, {} (empty initializer) is an error C99.Pulley
However, here is something great for you: The standard allows specifying named members multiple times, the later override. So for named-parameters only you can solve the defaults problem and allow for an empty call. #define vrange(...) CALL(range,(param){.from=1, .to=100, .step=1, __VA_ARGS__})Pulley
I hope the compiler errors are readable, but this is a great technique! Almost looks like python kwargs.Displace
Answer with 2 different function names is a better, simpler way of accomplishing the same goal!Meaghan
Awesome solution. But it gives a missing initializer for field warning should just ignore thatFruiterer
@Meaghan While certainly simpler, it is not objectively better; named parameters come with benefits such as ease of readability of calls (at the expense of readability of source code). One is better for developers of the source, the other is better for users of the function. It's a little hasty to just throw out "this one is better!"Fervidor
Clever. Unfortunately doesn't interopt well with Emscripten (asm.js and Node.js) when calling the generated functions from Javascript. Thus I improved upon Jens Gustedt’s answer, since it doesn't morph the compiler generated function.Porch
why, by default not specified arguments are 0 not a random number?Duffy
@DawidPi: C11 6.7.9(19), on initializing aggregates: "all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration" And as you know, static-duration elements are initialized to zero|NULL|\0. [This was in c99 too.]Aulic
Honestly a brilliant workaround to this missing functionality. Really great as an intellectual exercise. But there's no way I'm adding that much complication to my code - in particular dealing with documenting the functions and reduced readability. And all my junior devs shouting - quite reasonably - "wtf?!"Alehouse
You cannot call a regular function f(int a) with initializer syntax f(.a = 17). This makes it non-standard syntax and harder to read. Your solution does work but gcc -Wextra (which sets -Woverride-init) complains with if you use VA_ARGS inside the {} to override values.Planospore
There's a major pitfall ins this solution which prevents it to be a general one. The author also warns about it, ut only for the first argument. It lies in the fact that you must have a special value (0 in this case) for each argument which can be interpreted as "no value passed". This is not in generale possible as that value could be an intentional argument from the caller. In that case the "default" value would replace the one defined by the caller. Nice idea, though.Mcdermott
Denying that C has default arguments isn't "pessimism", it's realism! Techniques like the one illustrated here might qualify as nice puzzle solutions, but I can't imagine using them in any kind of practical programming. If something like this came up in a code review, the meeting would grind to a screeching halt with stern lectures all around about obfuscated code, wasted time, and unmaintainability.Burchfield
Very interesting solution is suggested here: https://mcmap.net/q/67629/-optional-parameters-with-c-macrosTrichina
G
189

Yes. :-) But not in a way you would expect.

int f1(int arg1, double arg2, char* name, char *opt);

int f2(int arg1, double arg2, char* name)
{
  return f1(arg1, arg2, name, "Some option");
}

Unfortunately, C doesn't allow you to overload methods so you'd end up with two different functions. Still, by calling f2, you'd actually be calling f1 with a default value. This is a "Don't Repeat Yourself" solution, which helps you to avoid copying/pasting existing code.

Gil answered 24/9, 2009 at 15:6 Comment(3)
FWIW, I'd prefer use the number at the end of the function to indicate the number of args it takes. Makes it easier than just use any arbitrary number. :)Ephraim
This is by far the best answer because it demonstrates a simple way to accomplish the same goal. I have a function that is part of a fixed API that I don't want to change, but I need it to take a new param. Of course, it is so blindingly obvious that I missed it (got stuck on thinking of the default param!)Meaghan
f2 could also be a preprocessor macroRolanderolando
A
171

Not really. The only way would be to write a varargs function and manually fill in default values for arguments which the caller doesn't pass.

Aberration answered 24/9, 2009 at 14:40 Comment(10)
I hate the lack of checking when using varargs.Striction
As well you should; I actually don't recommend this; I just wanted to convey that it is possible.Aberration
However, how do you wanna check whether the caller passes the argument or not? I think for this to work, don't you have the caller to tell you that he didn't pass it? I think this makes the whole approach somewhat less usable - the caller could aswell call a function with another name.Hujsak
That is definitely the problem, since there's no reliable, cross-platform way to check whether anything was passed at all or how many arguments they sent you. So varargs might work well if you have a function where it makes sense to call it like f(5, 6, 7, NULL) with some kind of terminating argument. I do occasionally write functions for which this might make sense, though not often, which is why I started my answer by saying, "Not really."Aberration
The open(2) system call uses this for an optional argument that may be present depending on the required arguments, and printf(3) reads a format string that specifies how many arguments there will be. Both use varargs quite safely and effectively, and though you can certainly screw them up, printf() especially seems to be quite popular.Akiko
Printf is actually a bad example because C compilers actually end up checking the number of arguments you pass to printf and giving you errors if you pass the wrong number. The varargs function itself is not able to do that, since there's no function or macro to tell you how many parameters were actually passed.Aberration
@Eli: Not all C compilers are gcc. There's some advanced compiler magic going on for it to warn when your printf() args don't match your format string. And I don't think it's possible to get similar warnings for your own variadic functions (unless they use the same style of format string).Ediva
@BenjaminGruenbaum: Good catch, I've updated the link to point to Wikipedia.Aberration
does anyone have an implementation of this? even if it's BAD idea.Fruiterer
How is it possible that there are two open() functions with the same name? int open(const char *pathname, int flags) and int open(const char *pathname, int flags, mode_t mode); (see man 2 open)Genny
P
49

We can create functions which use named parameters (only) for default values. This is a continuation of bk.'s answer.

#include <stdio.h>                                                               

struct range { int from; int to; int step; };
#define range(...) range((struct range){.from=1,.to=10,.step=1, __VA_ARGS__})   

/* use parentheses to avoid macro subst */             
void (range)(struct range r) {                                                     
    for (int i = r.from; i <= r.to; i += r.step)                                 
        printf("%d ", i);                                                        
    puts("");                                                                    
}                                                                                

int main() {                                                                     
    range();                                                                    
    range(.from=2, .to=4);                                                      
    range(.step=2);                                                             
}    

The C99 standard defines that later names in the initialization override previous items. We can also have some standard positional parameters as well, just change the macro and function signature accordingly. The default value parameters can only be used in named parameter style.

Program output:

1 2 3 4 5 6 7 8 9 10 
2 3 4 
1 3 5 7 9
Pulley answered 29/10, 2011 at 5:14 Comment(1)
This seems like an easier and more straight forward implementation than the Wim ten Brink or BK solution. Are there any downsides to this implementation that the others do not also posses?Faceplate
N
24

OpenCV uses something like:

/* in the header file */

#ifdef __cplusplus
    /* in case the compiler is a C++ compiler */
    #define DEFAULT_VALUE(value) = value
#else
    /* otherwise, C compiler, do nothing */
    #define DEFAULT_VALUE(value)
#endif

void window_set_size(unsigned int width  DEFAULT_VALUE(640),
                     unsigned int height DEFAULT_VALUE(400));

If the user doesn't know what he should write, this trick can be helpful:

usage example

Nerta answered 18/12, 2012 at 19:38 Comment(1)
This was a C question and the solution does not provide default values for C. Compiling your C code as C++ is not really that interesting, then you might as well use the default values that C++ provides. Also, C code is not always valid C++ code so it implies a porting effort.Planospore
P
20

No.

Not even the very latest C99 standard supports this.

Prismatoid answered 24/9, 2009 at 14:39 Comment(3)
a simple no would have been even better ;)Cummerbund
@kevindtimm: That's not possible, SO mandates a minimum-length on answers. I tried. :)Prismatoid
Please refer to my answer. :)Rochelle
V
18

No, that's a C++ language feature.

Virgule answered 24/9, 2009 at 14:39 Comment(0)
M
17

Probably the best way to do this (which may or may not be possible in your case depending on your situation) is to move to C++ and use it as 'a better C'. You can use C++ without using classes, templates, operator overloading or other advanced features.

This will give you a variant of C with function overloading and default parameters (and whatever other features you chose to use). You just have to be a little disciplined if you're really serious about using only a restricted subset of C++.

A lot of people will say it's a terrible idea to use C++ in this way, and they might have a point. But's it's just an opinion; I think it's valid to use features of C++ that you're comfortable with without having to buy into the whole thing. I think a significant part of the reason for the sucess of C++ is that it got used by an awful lot of programmers in it's early days in exactly this way.

Mountainside answered 24/9, 2009 at 18:14 Comment(0)
S
16

Short answer: No.

Slightly longer answer: There is an old, old workaround where you pass a string that you parse for optional arguments:

int f(int arg1, double arg2, char* name, char *opt);

where opt may include "name=value" pair or something, and which you would call like

n = f(2,3.0,"foo","plot=yes save=no");

Obviously this is only occasionally useful. Generally when you want a single interface to a family of functionality.


You still find this approach in particle physics codes that are written by professional programs in c++ (like for instance ROOT). It's main advantage is that it may be extended almost indefinitely while maintaining back compatibility.

Striction answered 24/9, 2009 at 14:39 Comment(3)
Combine this with varargs and you've got all kinds of fun!Melonymelos
I would use a custom struct and have the caller make one, fill in the fields for different options, and then pass it by address, or pass NULL for default options.Akiko
Copying code patterns from ROOT is a terrible idea!Roumell
S
16

Another trick using macros:

#include <stdio.h>

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

int (func)(int a, int b)
{
    return a + b;
}

int main(void)
{
    printf("%d\n", func(1));
    printf("%d\n", func(1, 2));
    return 0;
}

If only one argument is passed, b receives the default value (in this case 15)

Schwa answered 2/10, 2018 at 14:12 Comment(2)
at FUNC(VA_ARGS, 15, 0), it ithe last param mandatory, that "0"? I've tried without it and seemed to work fine.Conias
@Conias it is mandatory if you don't compile with gcc, gcc allows to include ... and pass only 2 parameters (in this case) as an extension, compile with -pedantic and see what happens.Schwa
A
15

Yet another option uses structs:

struct func_opts {
  int    arg1;
  char * arg2;
  int    arg3;
};

void func(int arg, struct func_opts *opts)
{
    int arg1 = 0, arg3 = 0;
    char *arg2 = "Default";
    if(opts)
      {
        if(opts->arg1)
            arg1 = opts->arg1;
        if(opts->arg2)
            arg2 = opts->arg2;
        if(opts->arg3)
            arg3 = opts->arg3;
      }
    // do stuff
}

// call with defaults
func(3, NULL);

// also call with defaults
struct func_opts opts = {0};
func(3, &opts);

// set some arguments
opts.arg3 = 3;
opts.arg2 = "Yes";
func(3, &opts);
Akiko answered 24/9, 2009 at 19:49 Comment(0)
R
9

No.

Rochelle answered 24/9, 2009 at 15:1 Comment(2)
what is the workaround? I can see that it is 20202020 in hex, but how do I type it?Platysma
@Platysma those would be ASCII spaces, no?Harrell
F
6

No, but you might consider using a set of functions (or macros) to approximate using default args:

// No default args
int foo3(int a, int b, int c)
{
    return ...;
}

// Default 3rd arg
int foo2(int a, int b)
{
    return foo3(a, b, 0);  // default c
}

// Default 2nd and 3rd args
int foo1(int a)
{
    return foo3(a, 1, 0);  // default b and c
}
Faradize answered 24/9, 2009 at 16:32 Comment(0)
J
5

Yes, with features of C99 you may do this. This works without defining new data structures or so and without the function having to decide at runtime how it was called, and without any computational overhead.

For a detailed explanation see my post at

http://gustedt.wordpress.com/2010/06/03/default-arguments-for-c99/

Jens

Jamestown answered 14/6, 2010 at 13:56 Comment(2)
Seel also my answer which is derived from yours.Porch
Inline an example.Yevette
P
4

I improved Jens Gustedt’s answer so that:

  1. inline functions aren’t employed
  2. defaults are computed during preprocessing
  3. modular reuseable macros
  4. possible to set compiler error that meaningfully matches the case of insufficient arguments for the allowed defaults
  5. the defaults aren’t required to form the tail of the parameter list if the argument types will remain unambiguous
  6. interopts with C11 _Generic
  7. vary the function name by the number of arguments!

variadic.h:

#ifndef VARIADIC

#define _NARG2(_0, _1, _2, ...) _2
#define NUMARG2(...) _NARG2(__VA_ARGS__, 2, 1, 0)
#define _NARG3(_0, _1, _2, _3, ...) _3
#define NUMARG3(...) _NARG3(__VA_ARGS__, 3, 2, 1, 0)
#define _NARG4(_0, _1, _2, _3, _4, ...) _4
#define NUMARG4(...) _NARG4(__VA_ARGS__, 4, 3, 2, 1, 0)
#define _NARG5(_0, _1, _2, _3, _4, _5, ...) _5
#define NUMARG5(...) _NARG5(__VA_ARGS__, 5, 4, 3, 2, 1, 0)
#define _NARG6(_0, _1, _2, _3, _4, _5, _6, ...) _6
#define NUMARG6(...) _NARG6(__VA_ARGS__, 6, 5, 4, 3, 2, 1, 0)
#define _NARG7(_0, _1, _2, _3, _4, _5, _6, _7, ...) _7
#define NUMARG7(...) _NARG7(__VA_ARGS__, 7, 6, 5, 4, 3, 2, 1, 0)
#define _NARG8(_0, _1, _2, _3, _4, _5, _6, _7, _8, ...) _8
#define NUMARG8(...) _NARG8(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define _NARG9(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, ...) _9
#define NUMARG9(...) _NARG9(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define __VARIADIC(name, num_args, ...) name ## _ ## num_args (__VA_ARGS__)
#define _VARIADIC(name, num_args, ...) name (__VARIADIC(name, num_args, __VA_ARGS__))
#define VARIADIC(name, num_args, ...) _VARIADIC(name, num_args, __VA_ARGS__)
#define VARIADIC2(name, num_args, ...) __VARIADIC(name, num_args, __VA_ARGS__)

// Vary function name by number of arguments supplied
#define VARIADIC_NAME(name, num_args) name ## _ ## num_args ## _name ()
#define NVARIADIC(name, num_args, ...) _VARIADIC(VARIADIC_NAME(name, num_args), num_args, __VA_ARGS__)

#endif

Simplified usage scenario:

const uint32*
uint32_frombytes(uint32* out, const uint8* in, size_t bytes);

/*
The output buffer defaults to NULL if not provided.
*/

#include "variadic.h"

#define uint32_frombytes_2(   b, c) NULL, b, c
#define uint32_frombytes_3(a, b, c)    a, b, c
#define uint32_frombytes(...) VARIADIC(uint32_frombytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

And with _Generic:

const uint8*
uint16_tobytes(const uint16* in, uint8* out, size_t bytes);

const uint16*
uint16_frombytes(uint16* out, const uint8* in, size_t bytes);

const uint8*
uint32_tobytes(const uint32* in, uint8* out, size_t bytes);

const uint32*
uint32_frombytes(uint32* out, const uint8* in, size_t bytes);

/*
The output buffer defaults to NULL if not provided.
Generic function name supported on the non-uint8 type, except where said type
is unavailable because the argument for output buffer was not provided.
*/

#include "variadic.h"

#define   uint16_tobytes_2(a,    c) a, NULL, c
#define   uint16_tobytes_3(a, b, c) a,    b, c
#define   uint16_tobytes(...) VARIADIC(  uint16_tobytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

#define uint16_frombytes_2(   b, c) NULL, b, c
#define uint16_frombytes_3(a, b, c)    a, b, c
#define uint16_frombytes(...) VARIADIC(uint16_frombytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

#define   uint32_tobytes_2(a,    c) a, NULL, c
#define   uint32_tobytes_3(a, b, c) a,    b, c
#define   uint32_tobytes(...) VARIADIC(  uint32_tobytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

#define uint32_frombytes_2(   b, c) NULL, b, c
#define uint32_frombytes_3(a, b, c)    a, b, c
#define uint32_frombytes(...) VARIADIC(uint32_frombytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

#define   tobytes(a, ...) _Generic((a),                                                                                                 \
                                   const uint16*: uint16_tobytes,                                                                       \
                                   const uint32*: uint32_tobytes)  (VARIADIC2(  uint32_tobytes, NUMARG3(a, __VA_ARGS__), a, __VA_ARGS__))

#define frombytes(a, ...) _Generic((a),                                                                                                 \
                                         uint16*: uint16_frombytes,                                                                     \
                                         uint32*: uint32_frombytes)(VARIADIC2(uint32_frombytes, NUMARG3(a, __VA_ARGS__), a, __VA_ARGS__))

And with variadic function name selection, which can't be combined with _Generic:

// winternitz() with 5 arguments is replaced with merkle_lamport() on those 5 arguments.

#define   merkle_lamport_5(a, b, c, d, e) a, b, c, d, e
#define   winternitz_7(a, b, c, d, e, f, g) a, b, c, d, e, f, g
#define   winternitz_5_name() merkle_lamport
#define   winternitz_7_name() winternitz
#define   winternitz(...) NVARIADIC(winternitz, NUMARG7(__VA_ARGS__), __VA_ARGS__)
Porch answered 18/11, 2015 at 17:51 Comment(0)
V
3

Generally no, but in gcc You may make the last parameter of funcA() optional with a macro.

In funcB() i use a special value (-1) to signal that i need the default value for the 'b' parameter.

#include <stdio.h> 

int funcA( int a, int b, ... ){ return a+b; }
#define funcA( a, ... ) funcA( a, ##__VA_ARGS__, 8 ) 


int funcB( int a, int b ){
  if( b == -1 ) b = 8;
  return a+b;
}

int main(void){
  printf("funcA(1,2): %i\n", funcA(1,2) );
  printf("funcA(1):   %i\n", funcA(1)   );

  printf("funcB(1, 2): %i\n", funcB(1, 2) );
  printf("funcB(1,-1): %i\n", funcB(1,-1) );
}
Video answered 24/9, 2009 at 16:48 Comment(0)
S
2

YES

Through macros

3 Parameters:

#define my_func2(...) my_func3(__VA_ARGS__, 0.5)
#define my_func1(...) my_func2(__VA_ARGS__, 10)
#define VAR_FUNC(_1, _2, _3, NAME, ...) NAME
#define my_func(...) VAR_FUNC(__VA_ARGS__, my_func3, my_func2, my_func1)(__VA_ARGS__)

void my_func3(char a, int b, float c) // b=10, c=0.5
{
    printf("a=%c; b=%d; c=%f\n", a, b, c);
}

If you want 4th argument, then an extra my_func3 needs to be added. Notice the changes in VAR_FUNC, my_func2 and my_func

4 Parameters:

#define my_func3(...) my_func4(__VA_ARGS__, "default") // <== New function added
#define my_func2(...) my_func3(__VA_ARGS__, (float)1/2)
#define my_func1(...) my_func2(__VA_ARGS__, 10)
#define VAR_FUNC(_1, _2, _3, _4, NAME, ...) NAME
#define my_func(...) VAR_FUNC(__VA_ARGS__, my_func4, my_func3, my_func2, my_func1)(__VA_ARGS__)

void my_func4(char a, int b, float c, const char* d) // b=10, c=0.5, d="default"
{
    printf("a=%c; b=%d; c=%f; d=%s\n", a, b, c, d);
}

Only exception that float variables cannot be given default values (unless if it is the last argument as in the 3 parameters case), because they need period ('.'), which is not accepted within macro arguments. But can figure out a work around as seen in my_func2 macro (of 4 parameters case)

Program

int main(void)
{
    my_func('a');
    my_func('b', 20);
    my_func('c', 200, 10.5);
    my_func('d', 2000, 100.5, "hello");

    return 0;
}

Output:

a=a; b=10; c=0.500000; d=default                                                                                                                                                  
a=b; b=20; c=0.500000; d=default                                                                                                                                                  
a=c; b=200; c=10.500000; d=default                                                                                                                                                
a=d; b=2000; c=100.500000; d=hello  
Schism answered 23/7, 2018 at 8:6 Comment(0)
E
1

There's a trick I've occasionally used, which has been available since C99, using variadic macros, compound literals and designated initializers. As with any macro solution, it is cumbersome and generally not recommended other than as a last resort...

My method is built in the following way:

  • Wrap the actual function in a function-like, variadic macro:

    void myfunc (int x, int y)         // actual function
    #define myfunc(...) myfunc(params) // wrapper macro
    
  • By using compound literals, copy down the parameters passed into a temporary object. This object should be a private struct corresponding directly to the function's expected parameter list. Example:

    typedef struct
    {
      int x;
      int y;
    } myfunc_t;
    
    #define PASSED_ARGS(...) (myfunc_t){__VA_ARGS__}
    

    This means that the same type safety ("as per assignment") rules used when passing parameters to a function is also used when initializing this struct. We don't lose any type safety. Similarly, this automatically guards against providing too many arguments.

  • However, the above doesn't cover the case of an empty argument list. To counter this, add a dummy argument so that the initializer list is never empty:

    typedef struct
    {
      int dummy;
      int x;
      int y;
    } myfunc_t;
    
    #define PASSED_ARGS(...) (myfunc_t){0,__VA_ARGS__}
    
  • Similarly, we can count the number of arguments passed, assuming that every parameter passed can get implicitly converted to int:

    #define COUNT_ARGS(...) (sizeof(int[]){0,__VA_ARGS__} / sizeof(int) - 1)

  • We define a macro for the default arguments #define DEFAULT_ARGS (myfunc_t){0,1,2}, where 0 is the dummy and 1,2 are the default ones.

  • Wrapping all of this together, the outermost wrapper macro may look like:

    #define myfunc(...) myfunc( MYFUNC_INIT(__VA_ARGS__).x, MYFUNC_INIT(__VA_ARGS__).y )

    This assuming that the inner macro MYFUNC_INIT returns a myfunc_t struct.

  • The inner macro conditionally picks struct initializers based on the size of the argument list. In case the argument list is short, it fills up with default arguments.

    #define MYFUNC_INIT(...) \
      (myfunc_t){ 0,         \
                  .x = COUNT_ARGS(__VA_ARGS__)==0 ? DEFAULT_ARGS.x : PASSED_ARGS(__VA_ARGS__).x, \
                  .y = COUNT_ARGS(__VA_ARGS__)<2  ? DEFAULT_ARGS.y : PASSED_ARGS(__VA_ARGS__).y, \
                }
    

Full example:

#include <stdio.h>

void myfunc (int x, int y)
{
  printf("x:%d y:%d\n", x, y);
}

typedef struct
{
  int dummy;
  int x;
  int y;
} myfunc_t;

#define DEFAULT_ARGS (myfunc_t){0,1,2}
#define PASSED_ARGS(...) (myfunc_t){0,__VA_ARGS__}
#define COUNT_ARGS(...) (sizeof(int[]){0,__VA_ARGS__} / sizeof(int) - 1)
#define MYFUNC_INIT(...) \
  (myfunc_t){ 0,         \
              .x = COUNT_ARGS(__VA_ARGS__)==0 ? DEFAULT_ARGS.x : PASSED_ARGS(__VA_ARGS__).x, \
              .y = COUNT_ARGS(__VA_ARGS__)<2  ? DEFAULT_ARGS.y : PASSED_ARGS(__VA_ARGS__).y, \
            }

#define myfunc(...) myfunc( MYFUNC_INIT(__VA_ARGS__).x, MYFUNC_INIT(__VA_ARGS__).y )

int main (void)
{
  myfunc(3,4);
  myfunc(3);
  myfunc();
}

Output:

x:3 y:4
x:3 y:2
x:1 y:2

Godbolt: https://godbolt.org/z/4ns1zPW16 As you can see from the -O3 disassembly, there is zero overhead from the compound literals.


I noticed that my method reminds a bit of the current, top-voted answer. For comparison with other solutions here:

Pros:

  • Pure, portable standard ISO C, no dirty gcc extensions, no poorly-defined behavior.
  • Can handle empty argument lists.
  • Efficient, zero overhead, doesn't rely on function inlining getting carried out as expected.
  • No obscure designated initializers on the caller-side.

Cons:

  • Relies on every parameter being implicitly convertible to int, which often isn't the case. For example strict C does not allow implicit conversions from pointers to int - such implicit conversions is a non-conforming (but popular) compiler extension.
  • Default args and structs have to be generated per function. Although not covered by this answer, this could be automated with X macros. But doing so will also reduce readability even further.
Embody answered 3/10, 2022 at 10:30 Comment(0)
D
0

Yes you can do somthing simulair, here you have to know the different argument lists you can get but you have the same function to handle then all.

typedef enum { my_input_set1 = 0, my_input_set2, my_input_set3} INPUT_SET;

typedef struct{
    INPUT_SET type;
    char* text;
} input_set1;

typedef struct{
    INPUT_SET type;
    char* text;
    int var;
} input_set2;

typedef struct{
    INPUT_SET type;
    int text;
} input_set3;

typedef union
{
    INPUT_SET type;
    input_set1 set1;
    input_set2 set2;
    input_set3 set3;
} MY_INPUT;

void my_func(MY_INPUT input)
{
    switch(input.type)
    {
        case my_input_set1:
        break;
        case my_input_set2:
        break;
        case my_input_set3:
        break;
        default:
        // unknown input
        break;
    }
}
De answered 25/9, 2009 at 11:2 Comment(0)
Q
0

you don't need to use VARARGS with just C. Here is an example.

int funcA_12(int a1, int a2) { ... }

#define funcA(a1) funcA_12(a1, 0)

This answer is very similar to the two functions method above but in this case, you're using a macro for the function name that defines the arguments.

Quadriplegic answered 2/9, 2021 at 13:34 Comment(0)
V
0

https://github.com/cindRoberta/C/blob/master/structure/function/default_parameter.c

#include<stdio.h>

void f_impl(int a, float b) {
  printf("%d %g\n", a, b);
}

#define f_impl(...) f_macro(__VA_ARGS__, 3.7)
#define f_macro(a, b, ...) f_impl(a, b)

int main(void) {
  f_impl(1);
  f_impl(1, 2, 3, 4);

  return 0;
}
Valuable answered 22/11, 2021 at 16:9 Comment(0)
K
0

I know how to do this in a better manner. You simply assign NULL to a parameter, so, you will have no value. Then you check if the parameter value is NULL, you change it to the default value.

void func(int x){
if(x == NULL)
  x = 2;
....
}

Though, it will cause warnings. a better choice would be to assign a value that will do nothing if the parameter value is that:

void func(int x){
if(x == 1)
  x = 2;
....
}

In the example above, if x is 1 the function changes it to 2;

Thanks to @user904963, EDIT: if you have to cover all ranges of numbers, it's not hard to add another argument only to say to the function whether it would set the parameter to default or not

void func(int x, bool useDefault){
if(useDefault) //useDefault == true
  x = 2;
....
}

However, remember to include stdbool.h

Kiehl answered 23/2, 2022 at 11:17 Comment(2)
In your first example, x == NULL will only be true if x is already 0, so the code doesn't give a default value to x. The second example could work, but it easily could not if the argument taken in can be the full range of values.Lubet
Adding a boolean parameter flag is OK, if you only have one parameter that can hold a default, but it gets unwieldy if you need all parameters to have such a flag! A NULL denoting default is better...Candlepower
I
-1

I made it appropriately by bk. and Eric.

#include <stdio.h>

// 구조체 생성
typedef struct range {
  int a;
} f_args;

// 매개변수 기본값 설정
#define func(...) func((f_args){.a = 20, __VA_ARGS__})
f_args(func)(f_args x);

int main(void) {
  // 매개변수 기본값 설정(선택 1)
  f_args r = func();

  // 매개변수 값 변환(선택 2)
  // f_args r = func(.a = 10);

  printf("%d ", r.a); //확인

  return 0;
}

// 매개변수 기본값 구성 가능한 함수
f_args(func)(f_args x) {
  printf("%d ", x.a); //확인
  x.a = x.a + 10;

  return x;
}

The default value must be changed in #define (variadic macros)

Intact answered 8/12, 2023 at 3:42 Comment(0)
M
-6

Why can't we do this.

Give the optional argument a default value. In that way, the caller of the function don't necessarily need to pass the value of the argument. The argument takes the default value. And easily that argument becomes optional for the client.

For e.g.

void foo(int a, int b = 0);

Here b is an optional argument.

Mastrianni answered 22/8, 2013 at 11:46 Comment(1)
Stunning insight, the problem is that C doesn't support optional arguments or overloaded functions, so the direct solution does not compile.Halliehallman

© 2022 - 2024 — McMap. All rights reserved.