How to create a default parameter value for a function in C++

Overview

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.

Creating a default parameter

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.

Syntax

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.

Code example

#include <iostream>
#include <string>
using namespace std;
void myfunction(string myname = "Theophilus") {
cout << myname << " Onyejiaku\n";
}
int main() {
// calling the function without an argument
myfunction();
// calling the function with arguments
myfunction("Chidalu");
myfunction("Okonkwo");
return 0;
}

Code explanation

  • Line 5: We create a function, myfunction, with a parameter myname that has Theophilus as a default argument.
  • Line 6: We write a block to return whenever the myfunction() function is called in the code.
  • Line 11: We call the myfunction function without passing an argument to it. This returns the default argument that was passed to the function earlier.
  • Line 14: We call the function again and this time, we pass the argument "Chidalu" to it.
  • Line 15: We call the function a third time and this time, we pass the argument "Okonkwo" to it.

Free Resources