Wednesday, August 31, 2011

Default argument in functions in C++ Programs


In this blog, today I will discuss about an unique feature of C++

C++ allows us to call a function without specifying all the arguments. The function declaration must provide default values for those arguments that are not specified. But there is an option- if we call the function with argument instead of the default value then the argument value will be active. The declaration of such functions will be like: -
int add (int a, float b=10);

This means that we can call the function only with an integer argument although the function will work with the two values, the second value being the float value-10. If we call the function like this: - add (3,2.5); then the function will reject the default value and will work with the values- 3 and 2.5

One very important point to be noted that only the trailing arguments can have default values. That is, we must add defaults from the right to left.

int add (int a, float b=10) // legal
int add (int a=5,float b) //illegal

Here is another C++ program on default argument function

#include<iostream.h>
#include<conio.h>
float cal (float amt, int year, float rate=15);
void prn (char c=’*’);
void main ()
{
float amount, interest;
int year;
cout<< ”Enter the amount on which interest has to be calculated: -“;
cin>>amount;
cout<<”Enter the number of years: -“;
cin>>year;
interest=cal (amount, year);
prn ();
cout<< ”The interest on-“<< amount<< ”-for the period of-“<< year<< ” years would be—“<< interest<< endl;
prn (‘-‘);
getch ();
}
float cal (float amt, int year, float rate)
{
float sum=amt;
for (int i=1; i< =year; i++)
{
sum=sum * (1+ (rate/100));
}
return sum-amt;
}
void prn (char c)
{
for (int i=0; i<40; i++)
{
cout<< c;
}
cout<< endl;
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner