Arnav Borborah Arnav Borborah - 3 months ago 10
C++ Question

Specifying default parameter when calling C++ function

Suppose I have code like this:

void f(int a = 0, int b = 0, int c = 0)
{
//...Some Code...
}


As you can evidently see above with my code, the parameters
a
,
b
, and
c
have default parameter values of 0. Now take a look at my main function below:

int main()
{
//Here are 4 ways of calling the above function:
int a = 2;
int b = 3;
int c = -1;

f(a, b, c);
f(a, b);
f(a);
f();
//note the above parameters could be changed for the other variables
//as well.
}


Now I know that I can't just skip a parameter, and let it have the default value, because that value would evaluate as the parameter at that position. What I mean is, that I cannot, say call,
f(a,c)
, because,
c
would be evaluated as
b
, which is what I don't want, especially if
c
is the wrong type. Is there a way for the calling function to specify in C++, to use whatever default parameter value there is for the function in any given position, without being limited to going backwards from the last parameter to none? Is there any reserved keyword to achieve this, or at least a work-around? An example I can give would be like:

f(a, def, c) //Where def would mean default.

Answer

There isn't a reserved word for this, and f(a,,c) is not valid either. You can omit a number of rightmost optional parameters, as you show, but not the middle one like that.

http://www.learncpp.com/cpp-tutorial/77-default-parameters/

Quoting directly from the link above:

Multiple default parameters

A function can have multiple default parameters:

void printValues(int x=10, int y=20, int z=30)
{
    std::cout << "Values: " << x << " " << y << " " << z << '\n';
}

Given the following function calls:

printValues(1, 2, 3);
printValues(1, 2);
printValues(1);
printValues();

The following output is produced:

Values: 1 2 3
Values: 1 2 30
Values: 1 20 30
Values: 10 20 30

Note that it is impossible to supply a user-defined value for z without also supplying a value for x and y. This is because C++ does not support a function call syntax such as printValues(,,3). This has two major consequences:

1) All default parameters must be the rightmost parameters. The following is not allowed:

void printValue(int x=10, int y); // not allowed

2) If more than one default parameter exists, the leftmost default parameter should be the one most likely to be explicitly set by the user.

Comments