Passing default value to function

Passing default value to function is simple and easy implementation of function.

In this tutorial we will see what is function, what is default argument , how to pass default arguments in c++and default arguments in c++ program.

Default arguments in c++ : Default arguments are those arguments to whom values are given at the time of function declaration.

If the function call does not mention the argument to whom default argument is given then the default value is used in the function called.

and if the value for that argument is given in the function called then that value takes precision(priority) over default argument.

Algorithm to pass default argument to function

  1. Start
  2. Define function which argument contains default value
  3. Write main function
  4. Pass number (if you want to change default value)  and call function
  5. End

Program using functions with default arguments in c++

123456789101112131415#include <iostream>using namespace std;int sum(int x, int y, int z=0, int w=0){    return (x + y + z + w);} int main(){    cout<<“Default arguments”<<“\n”;    cout <<“sum = “<<sum(10, 15) << endl;    return 0;}

Output :

Default Arguments in C++
Default Arguments in C++

Explanation :

1. Execution starts with the main function.

2. Print statement in main.

3. Call the function by passing 2 values to function.

sum(10, 15)  => control goes to function

int sum(int x, int y, int z=0, int w=0)  => functions has 4 arguments in which 2 argument not having default values and remaining of two has default values

=> x = 10, y=15,z=0,w=0

return (x + y + z + w);   => returns 25 by adding numbers

}  => function returned to main function

4. Print the value returned by function.