Can I set default values in C functions? I want to call foo(par 1, par 2). But I also…
- User
Can I set default values in C functions? I want to call foo(par 1, par 2). But I also want to call foo(par 1, par 2, par 3), where par 3 is a default value if I don't set it in foo(par 1, par 2).
- Assistant
Short version
No. “Real” default-parameter syntax (like you have in C++, Python, etc.) does not exist in standard C. The language has only one function with a given name, so you can’t writevoid foo(int par1, int par2, int par3 = 42); /* <- illegal in C */
nor can you have two different functions called foo that take a different number of parameters (no over-loading).
What you can do instead ───────────────────────
- Write a thin wrapper with a different name:
#define DEFAULT_PAR3 42 void foo_full(int par1, int par2, int par3) { /* …real implementation… */ } void foo(int par1, int par2) /* “two-arg” version */ { foo_full(par1, par2, DEFAULT_PAR3); }- Use a macro as a front-end:
#define foo(p1, p2, ...) foo_full((p1), (p2), ##__VA_ARGS__, DEFAULT_PAR3)If the caller supplies a third argument, it’s used; if not, the macro tacks on DEFAULT_PAR3.
Be careful:
• Works only with GNU-style “##VA_ARGS” or C23’s__VA_OPT__(,)trick.
• Debuggers and editors will see the real function asfoo_full, notfoo.- Go the var-args route (
<stdarg.h>):
void foo(int par1, int par2, ...) /* any # of extra args */ { int par3 = DEFAULT_PAR3; va_list ap; va_start(ap, par2); if (va_arg(ap, int) != SENTINEL) /* you must know whether an arg exists */ par3 = va_arg(ap, int); va_end(ap); }But you still need some side channel (an explicit count, a sentinel value, or different format string) so the function knows whether a third argument was really supplied.
- Bundle the settings in a struct and pass a pointer, letting the caller fill only what they care about:
typedef struct { int par1; int par2; int par3; /* defaults to 42 */ } FooArgs; void foo(const FooArgs *a) { int p3 = a->par3 == 0 ? 42 : a->par3; … }Higher boilerplate, but scales well when parameters keep growing.
Bottom line
Standard C itself gives you no syntactic sugar for default values. You either: • create a wrapper with another name,
• hide that behind a macro,
• use var-args, or
• package the inputs in a struct. Choose whichever style best matches your project’s conventions and need for clarity/debug-friendliness.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.