Suppose there is a function with a default value:
int foo(int x=42);
If this is called by others like this:
int bar(int x=42) { return foo(x); }
int moo(int x=42) { return bar(x); }
This is of course just a contrived example. However, I sometimes have a quite similar situation. The parameter is just passed from the highest level (moo
) to the lowest and only there it is actually used. The bad thing about this is that when I change foo
to have a default different than 42
I would have to search for all callers and change the default value accordingly.
Is there some pattern/idiom to avoid this situation?
The only simple solution that comes to my mind is
int bar() { return foo(); }
int bar(int x) { return foo(x); }
However, as I am a bit lazy and in real code this would lead to quite some code duplication, I would like to avoid this.
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.
In JavaScript, default function parameters allow you to initialize named parameters with default values if no values or undefined are passed into the function.
I'd advise to select one of these two options below (as you can see in other answers - there are more possible solutions).
So, option 1 would looks like below:
int foo(int x=42);
int bar(int x) { return foo(x); }
int moo(int x) { return bar(x); }
int bar() { return foo(); }
int moo() { return bar(); }
And, option 2 will be a little shorter:
constexpr int FOO_DEFAULT = 42;
int foo(int x=FOO_DEFAULT);
int bar(int x=FOO_DEFAULT) { return foo(x); }
int moo(int x=FOO_DEFAULT) { return bar(x); }
I'd use option-1 for cases with small number of default values (like one default value), option-2 for cases where you have quite a few default values - like foo(int a, int b = 3, std::string c = "wow", float pi = 3.14)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With