11C++ Programming Default Arguments (Parameters)
11C++ Programming Default Arguments (Parameters)
(Parameters)
In this tutorial, we will learn C++ default arguments and their working with the
help of examples.
However, if arguments are passed while calling the function, the default
arguments are ignored.
We can understand the working of default arguments from the image above:
. When temp() is called, both the default parameters are used by the function.
. When temp(6) is called, the first argument becomes 6 while the default
value is used for the second parameter.
. When temp(6, -2.3) is called, both the default parameters are overridden,
resulting in i = 6 and f = -2.3 .
Therefore, 3.4 is passed as the first argument. Since the first argument has
been defined as int , the value that is actually passed is 3 .
#include <iostream>
using namespace std;
int main() {
int count = 5;
return 0;
}
Output
. display('#') is called with only one argument. In this case, the first becomes
'#' . The second default parameter n = 1 is retained.
We can also define the default parameters in the function definition itself. The
program below is equivalent to the one above.
#include <iostream>
using namespace std;
int main() {
int count = 5;
return 0;
}
Things to Remember
. Once we provide a default value for a parameter, all subsequent parameters
must also have default values. For example,
// Invalid
void add(int a, int b = 3, int c, int d);
// Invalid
void add(int a, int b = 3, int c, int d = 4);
// Valid
void add(int a, int c, int b = 3, int d = 4);
// Invalid code
int main() {
// function call
display();
}
Related Tutorials
Tutorials Examples
Join our newsle er for the latest Python 3 Tutorial Python Examples
updates.
JavaScript Tutorial JavaScript Examples
Swi Tutorial
C# Tutorial
DSA Tutorial
Company Apps
Privacy Policy
Contact
Blog
Youtube