Whenever a function is called within a code without passing an argument to it, the default argument passed to the default parameter when creating the function is returned.
To create a default parameter value, we make use of =
to assign a default argument to that specific parameter. Whenever the function that has this parameter is called within the code without passing an argument to it, it will return the default argument.
To create a default parameter with a default argument value to a function, we will use the syntax given in the code snippet below:
void nameoffunction(parameter = "defaultargument"){
// block of code to be executed
}
intmain(){
nameoffunction()
In the code written above, myfunction()
represents the function we created, parameter
represents the default parameter of the function, and "defaultargument"
represents the default argument that is passed to the function. We will call the function nameoffunction()
without passing an argument to it. Therefore, this will return the default argument we already passed to the function.
#include <iostream>#include <string>using namespace std;void myfunction(string myname = "Theophilus") {cout << myname << " Onyejiaku\n";}int main() {// calling the function without an argumentmyfunction();// calling the function with argumentsmyfunction("Chidalu");myfunction("Okonkwo");return 0;}
myfunction
, with a parameter myname
that has Theophilus
as a default argument.myfunction()
function is called in the code.myfunction
function without passing an argument to it. This returns the default argument that was passed to the function earlier."Chidalu"
to it."Okonkwo"
to it.