Wednesday, 28 March 2018

Default Arguments

C++ allows us to call a function without specifying all its arguments.

Default values are specified when function is declared.

Compiler looks at the prototype to see how many arguments, a function uses and alerts the program for possible default values.

Declaration of function with default values
   float amt(float prin_amt, int period, float rate = 0.12)

A function call
 float value = amt(500,7);
Passes value 500 to prin_amt and 7 to perod and then function uses 0.12 for rate.

A function call
float value = amt(500,7,0.15);
Passes explicit value of 0.15 to rate.

Only the trailing argument can have default values i.e. We can add default values from right to left. We can not provide default values in the middle of argument list.

#include<conio.h>
#include<iostream.h>
int volume(int len = 1, int wdt = 1, int hgt = 1);
void main( )
{
clrscr( )
{
cout<<"\n\n\tDefault box volume is--->"<<volume( );
cout<<"\n\n\tThe Volume with length 10 is--->"<<volume(10);
cout<<"\n\n\tThe Volume of the length 10 and width 10 is--->"<<volume(10,10);
cout<<"\n\n\tThe Volume with length 10, width 10 and height 10 is--->"<<volume(10,10,10);
getch( );
}
int volume(int len, int wdt, int hgt)
{
return(len*wdt*hgt);
}

Output:-
Default box volume is--->1
 The Volume with length 10 is--->10
 The Volume of the length 10 and width 10 is--->100
The Volume with length 10, width 10 and height 10 is--->1000

1 comment:

Popular Posts

Categories

Android (21) AngularJS (1) Books (3) C (75) C++ (81) Data Strucures (4) Engineering (13) FPL (17) HTML&CSS (38) IS (25) Java (85) PHP (20) Python (85) R (69) Selenium Webdriver (2) Software (13) SQL (27)