Reputation: 123
If I have a function such as
int mathscalc (int a, int b = 5)
{
}
And I call the function mathscalc(a), how can I only do 1 argument when it requires 2? if that's possible.
Upvotes: 0
Views: 132
Reputation: 15
Yes, those function calls are possible and are known as default arguments. The default arguments should be used in the last, the inverse of that ie.,
int mathscalc (int a = 5, int b)
is not possible.
If the corresponding function call is made as,
mathscalc (5,6); 'b' will take value 6,
else if it is made as mathscalc (5); 'b' will take the default value 5.
Upvotes: 0
Reputation: 1440
If you make call to mathscalc function with one say,
mathscalc(4);
Compiler intern changes this function with
mathscalc(4, 5);
But, if you make a call with two args say,
mathscalc(4, 10);
Compiler will not replace that b with 5 instead it uses 10 in the place of b.
Upvotes: 0
Reputation: 1079
b
has a default value. If it is not specified, it is 5, if it is specified, it is the value, that is given.
For example:
mathscalc(3, 10) // b is 10 inside the function call
mathscalc(3) // b is 5 inside the function call
Upvotes: 5
Reputation: 45470
This is well explained in C++11 Standard.
§8.3.6 Default arguments [dcl.fct.default]
1 If an initializer-clause is specified in a parameter-declaration this initializer-clause is used as a default argument. Default arguments will be used in calls where trailing arguments are missing.
2 [ Example: the declaration
void point(int = 3, int = 4);
declares a function that can be called with zero, one, or two arguments of type int. It can be called in any of these ways:
point(1,2); point(1); point();
The last two calls are equivalent to point(1,4) and point(3,4)
, respectively. —end example ]
3 A default argument shall be specified only in the parameter-declaration-clause of a function declaration or in a template-parameter (14.1); in the latter case, the initializer-clause shall be an assignment-expression. A default argument shall not be specified for a parameter pack. If it is specified in a parameter-declarationclause, it shall not occur within a declarator or abstract-declarator of a p*arameter-declaration*.
Upvotes: 1
Reputation: 68556
A value of 5 has been already assigned to the variable b
in your mathscalc
function.
So if you pass value 2 to a
, say the mathscalc
has a multiplication operation of c = a*b;
the result of c
will be 10.
If you explicitly pass a=2
and b=3
to your mathscalc
function, the existing value assigned to b=5
will be overwritten to b=3
, so the result of c
will be 6.
Upvotes: 0
Reputation: 27577
If you call mathscalc
with only one argument then b
will be set to it's default 5
.
Upvotes: 0