Cpp - Default Function Parameters

Introduction

If the function prototype declares a default value for a parameter, the function can be called without that parameter.

The default value is used whenever the parameter is omitted.

Here's a revised prototype of isLeapYear() that includes a default year:

bool isLeapYear(int year = 2016); 

If the isLeapYear() function is called without specifying a year, the default of 2016 is used.

A function's definition does not change when default parameters are declared in the prototype.

When a function has more than one parameter, default values are assigned based on the order of the parameters.

If a parameter does not have a default value, no previous parameter may have a default value.

For example, here's a prototype with four parameters:

long my_function(int x, int y, int z, int t); 

The following change is not permitted:

long my_function(int x, int y, int z = 1, int t); 

Here's a permitted prototype:

long my_function(int x, int y, int z = 1, int t = 2000); 

The function created from this prototype could be called with this statement:

my_function(130, 85); 

The argument values would be 130 for x, 85 for y, 1 for z, and 2000 for t.

The following code shows how to use default function parameter values.

Demo

#include <iostream> 
 
int findArea(int length, int width = 20, int height = 12); 
 
int main() /*  w ww .  j  a  v  a2 s .c  o  m*/
{ 
    int length = 100; 
    int width = 50; 
    int height = 2; 
    int area; 
 
    area = findArea(length, width, height); 
    std::cout << "First area: " << area << "\n\n"; 
 
    area = findArea(length, width); 
    std::cout << "Second area: " << area << "\n\n"; 
 
    area = findArea(length); 
    std::cout << "Third area: " << area << "\n\n"; 
    return 0; 
} 
 
int findArea(int length, int width, int height) 
{ 
    return (length * width * height); 
}

Result

The function computes the area of a cube.

If no height is provided, a height of 12 is used.

If no width is provided, a width of 20 and height of 12 are used.

Related Topic