Functions in C++: Return Type Function - Name (Typed Parameter List)
Functions in C++: Return Type Function - Name (Typed Parameter List)
Functions in C++: Return Type Function - Name (Typed Parameter List)
2.1 Introduction:-
Functions play an important role in C program development. Dividing a
program into functions is one of the major principles of top-down
structured programming. Another advantage of using functions is that it
is possible to reduce the size of a program by calling and using them at
different places in the program.
Ex:
float volume (int x , float y , float Z ) ;
Or
float volume (int , float , float ) ;
1
5- C++ supports passing arguments either , by value or by reference.
Example:
2
Note: C++ dictates that you either declare or define a function before
you use it. Declaring a function commonly called “prototype”.
Ex:
// prototype the function square
Ex
Inline double cube (double a )
{ return (a*a*a); }
3
The above inline function can be invoked by statements like.
c=cube (3.0);
d=cube (2.5+1.5);
Some of the situations where inline expansion may not work are:
1- For functions returning values, if a loop, a switch or a goto exists.
2- For functions not returning values, if a return statement exists.
3- If functions contain static variables.
4- If inline function are recursive.
Ex
# include <iostream.h>
# include <stdio.h>
inline float mul (float x, float y ) // inline function .
{ return (x*y); }
main( )
{
float a=12.343;
float b=9.82 ;
cout << mul (a,b)<< “\n” ;
cout <<div (a,b)<< “\n” ;
}
The output of above program is
121.227898
1.257128
4
2.4 Default Arguments:-
C++ allows us to call a function without specifying all its arguments. In
Such cases, the function assigns default value to the parameter which
does not have a matching argument in the function call. Default values
are specified when the function is declared.
Ex:
Prototype (i.e. function declaration) with default value.
Passes the value of 5000 to principal and 7 to period and them lets the
function use default value of 1.5 for rate.
Default arguments are useful in situations where some arguments
always have the same value. For instance, bank interest may remain the
same for all customers for a particular period of deposit. It also provides
a grater flexibility to the programmers.
5
////////////////////////////////// Default Arguments /////////////////////////////////
#include <iostream.h>
#include <stdio.h>
main( )
{
float amount;
float value (float p , int n, float r = 0.15 ); // prototype
void printline (char ch = ‘*’, int len = 40 ); // prototype
printline ( ); // uses default values for arguments
amount = value (5000.00,5);
cout<<``\n Final Value = ``<<amount <<``\n\n``;
printline (`=` ) ;
}