Default Arguments

In C++ a function can be called without specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching argument in the function call. The default value is specified when function is declared. 
           The default value is specified like the variable initialization. The prototype for the declaration of default value of an argument looks like float amount (float p, int time, float rate=0.10);
// declares a default value of 0.10 to the argument rate.

The call of this function as
value = amount (4000,5) ;// one argument missing for rate passes the value 4000 top, 5 to time and the function looks the prototype for missing argument that is declared as default value 0.10 the function uses the default value 0.10 for the third argument. But the call

value = amount (4000,5,0.15);
 no argument is missing, in this case function uses this value 0.15 for rate.
 Note : only the trailing arguments can have default value. We must add default from right to left. E.g.
int add( int  a,  int b =9, int  c= 10 );  // legal
int add(int a=8, int b, int c); // illegal
int add(int a, int b = 9, int c);  //illegal
int add( int a=8, int b=9,int c=10) // legal

Types of default arguments: -


Automatic
External
Static
Register
Mutable
Lifetime
Within function
Throughout the program
Throughout program
Within function
Apply only for object
Visibility
Within function








 Scope of variables: -
-          Local
-          Global
-          Class

o   Storage class

Storage class defines the variable visibility and lifetime.

//default arguments in function //define default values for arguments that are not passed when

//a function call is made

#include<iostream.h>

void marks_tot(int m1=40,int m2=40, int m3=40 );

void main()

{

//imagine 40 is given if absent in exam.

marks_tot();

marks_tot(55);

marks_tot(66,77);

marks_tot(75,85,92);

getch(); }

void marks_

tot(int m1, int m2, int m3)

{

cout<<"Total marks"<<(m1+m2+m3)< 

}

Const Arguments 

When arguments are passed by reference to the function, the function can modify the variables in the calling program. Using the constant arguments in the function, the variables in the calling program cannot be modified. const qualifier is used for it.  e.g.
 
#include<iostream.h>void func(int&,const int&);
void  main()
{ int a=10, b=20;
func(a,b);
}
void func(int& x, int &y)
{
x=100;  y=200; // error  since y is constant argument
}


Share To:

Arogya Thapa Magar

Post A Comment:

0 comments so far,add yours