I stumbled through an example from "Effective C++ in an Embedded Environment" by Scott Meyers where two ways of using default parameters were described: one which was described as costly and the other as a better option.
I am missing the explanation of why the first option might be more costly compared to the other one.
void doThat(const std::string& name = "Unnamed"); // Bad const std::string defaultName = "Unnamed"; void doThat(const std::string& name = defaultName); // Better
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.
There are no default parameters in C. One way you can get by this is to pass in NULL pointers and then set the values to the default if NULL is passed.
In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined .
Default parameter in Javascript The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
In the first one, a temporary std::string
is initialised from the literal "Unnamed"
each time the function is called without an argument.
In the second case, the object defaultName
is initialised once (per source file), and simply used on each call.
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