I want to achieve this:
- second parameter by default set to first argument
Something like:
int foo (int a, int b = a);
But how to do that?
Thanks a lot!
Generally no, but in gcc You may make the last parameter of funcA() optional with a macro.
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.
The Main Function in C Programming By default, the return type of the main function is int. There can be two types of main() functions: with and without parameters.
Default Arguments in C++ 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.
This is forbidden by:
9) Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in default argument expressions, even if they are not evaluated. Parameters of a function declared before a default argument expression are in scope and can hide namespace and class member names. [ Example:
int a;
int f(int a , int b = a); / / error: parameter a
/ / used as default argument
typedef int I;
int g( float I , int b = I (2)); / / error: parameter I found
int h(int a , int b = sizeof (a )); / / error, parameter a used
/ / in default argument
—end example ]
An alternative is overloading:
int foo(int a, int b);
int foo(int a)
{
return foo(a,a);
}
The reason this is disallowed has already been addressed, but another solution along the lines of @Vyktor's is to use boost::optional
instead of magic numbers (This has pros and cons compared to creating an overload):
int foo(int a, boost::optional<int> b = boost::none)
{
if(!b) b = a;
}
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