0% found this document useful (0 votes)
4 views55 pages

C++ Functions: Usage and Examples

Chapter 5 covers the use of functions in C++, including simple functions, passing arguments, function overloading, recursion, and inline functions. It explains how to define and call functions, pass variables by value and reference, and return values from functions. The chapter also discusses the benefits of function overloading and provides examples of various function implementations.

Uploaded by

ffizza76
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views55 pages

C++ Functions: Usage and Examples

Chapter 5 covers the use of functions in C++, including simple functions, passing arguments, function overloading, recursion, and inline functions. It explains how to define and call functions, pass variables by value and reference, and return values from functions. The chapter also discusses the benefits of function overloading and provides examples of various function implementations.

Uploaded by

ffizza76
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 5

Functions
Learning Objectives
• Use of functions in C++
C
• Simple functions
• Passing arguments to functions
• Create function overloads
• Recursion
• Write and use inline functions
• D f l A
Default Arguments
• Variables and Storage Class
FUNCTIONS
• A function groups a number of program
statements into a unit and gives it a name
• This unit can be invoked from other parts of
the program

Use of Function
• To aid in the conceptual organization of a
program
• To reduce program size
FUNCTIONS
Calling program

function
func1( );
void
id ffunc1
1()
{
Calls to f
func1(
1( );
)
function

}
func1( );

Same code is used


for all calls to function
Simple Functions
Semicolon
Return Type void func1( ); Function Declaration

void main( )
{

Semicolon
No Return Type func1 ( ); Function Call

} No semicolon
Return Type void func1( ) Declarator

Function Function
Body Definition

}
No semicolon
Function Definition
It contains the actual code of function
int ftoc (int temp)
{
int result= (temp-32)*5/9;
return result;
}

Function Definition Format

returntype functionname (parameterlist)


{
Statements;
}
parameterlist contains type and name of variables used in
the function
FUNCTION EXAMPLE
// [Link]
// demonstrates simple function
#include <iostream.h>

void starline(); //function declaration

int main()
{
starline(); //call to function
coutt << "Data
"D t ttype RRange"" << endl;
dl
starline(); //call to function
cout << "char -128 to 127" << endl
<< "short
short -32,768
-32 768 to 32
32,767
767" << endl
<< "int System dependent" << endl
<< "long -2, 147, 483, 648 to 2,147, 483, 647" << endl;
starline(); //call to function
return 0;
} Cont…..
FUNCTION EXAMPLE
//..................................................
//starline()
//function definition
void starline() //function declarator
{
for(int j=0; j<45; j++) //function body
cout << '*';
cout << endl;
}
Simple Functions Contd..
• Comparison with Library Functions
– The declaration is in the header file specified at
the beginning of the program
– The definition (compiled into executable code) is
in a library file that is linked automatically
• Eliminating
Eli i ti th the D
Declaration
l ti
– Place the definition (the function itself ) in the
b i i off program b
beginning before
f the
h fi
first callll to the
h
function
Eliminating the Declaration Example
// [Link]
// demonstrates function definition preceding function calls
#include <iostream.h>
//no function declaration
//...............................
// starline() () //f
//function definition
f
void starline()
{
for(int j=0; j<45; j++)
cout << '*'; '*'
cout << endl;
}
//............................................
i t main()
int i () //main()
// i () follows
f ll function
f ti
{
starline(); //call to function
cout << "Date type Range" << endl;
starline();
t li () //call
// ll to t function
f ti
cout << "char -128 to 127" << endl
<< "short -32, 768 to 32, 767" << endl
<< "int System dependent" << endl
<< "long
"l -2,
2 147147, 483
483, 648 tto 2 2, 147
147, 483
483, 647" << endl;
dl
starline(); //call to function
return 0;
}
Passing Arguments
Arg ments to F
Function
nction
• Constants
• Expressions
• Variables
– By value
– By reference
Passing Arguments to Functions Contd..

• The parameter of function are initialized


to the value of argument passed to it
• Function create copies of the arguments
passed to it, is called passing by value
• Passing other types of arguments
– Pointers and arrays
– Structures
St t
– Objects
Passing Constant Example
// [Link] //.................................
// demonstrates function arguments // repchar()
#include <iostream.h> // function definition
void repchar ((char ch, int n))
void repchar (char, int); {
//function declaration for (int j=0; j<n; j++)
int main( ) cout << ch;
{ cout << endl;
repchar('-' , 43); //call to }
function
cout << "Date type Range" << endl;
repchar('=', 23); // call to
function
cout << "char -128 to 127" << endl
<< "short -32, 768 to 32, 767" << endl
<< "int system dependent" << endl
<< "double
double -2,-2 147
147, 483
483, 648 to 2
2, 147
147, 483
483,
647" << endl;
repchar('-', 43); // call to
function
return 0;
}
Passing Variable Example
// [Link] //...................................
// demonstrates variable arguments // repchar()
#include <iostream> // function definition
using namespace std; void repchar (char ch ch, int n)
void repchar(char, int); {
int main() for(int j=0; j<n; j++) cout << ch;
{ cout << endl;
char chin; }
int nin;
cout << "Enter a character: ";
cin >> chin;
cout << "Enter number of times to
repeat it: ";
cin >>nin;
repchar(chin nin);
repchar(chin,
return 0;
}
Variable Passed by Value
Repchar (chin,nin);
This statement in
main()
() causes the
values in these
variables to be
copied into these
parameters in
main() repchar repchar()

chin ‘ ‘
‘=‘ ch
‘=‘ ‘=‘
nin n
30
--- 30--- -----------

Arguments Parameters
Example: Passing Variables
#i l d <iostream.h>
#include i t h

int ftoc (int); //function declaration

int main()
{
int ftemp;
cout << "Enter temperature in degree Fahrenhite: ";
cin >> ftemp;
int ctemp = ftoc(ftemp);
cout << "The temperature " <<ftemp<< " Degree Fahrenhite equals
"
<<ctemp<< " Degree Centigrade "<<endl;
return 0;
}
//..................................................
//function definition
int ftoc (int temp)
{
return (temp-32)*5/9;
}
Example: Passing constant, Variable & Expression
#include <iostream.h>

int square(int);
int main()
{
int x = 5, y= 7;
cout << square(9) <<endl
<< square (x) << endl
<<square (x+y) << endl
<< square (x+y+7) <<endl;

return 0;
}

int square(int a)

{
return
t a **=a;
}
Returning Values from Function
• Return value consist of an answer to the
problem the function has solved
p
• When a function returns a value, the data
type of this value must be specified
• The function declaration does this by placing
the data type e.g.
eg
float lbstokg(float);
before the function name in the declaration
and the definition
Returning Values from Function
// [Link]
// demonstrates return values, converts pounds to kg
#include <iostream.h>

float lbstokg(float); //declaration

int main()
{
float lbs, kgs;
cout << "\nEnter your weight in pounds; ";
cin >> lbs;
kgs = lbstokg(lbs);
cout << "Your
Your weight in kilograms is " << kgs << endl;
return 0;
}
Returning Values from Function
//...................................
// lbstokg()
// converts pounds to kilograms
float lbstokg(float pounds)
{
fl t kil
float kilograms = 0 0.453592
453592 * pounds;
d
return kilograms;
}
The Return Statement
• The function lbstokg() is passed an argument
p
representingg a weight
g in p pounds,, which it
stores in the parameter pounds.
• The result is stored in the variable kilogram
• The value then returned to the calling
program using a return statement
return kilogram;
Return Statement
kgs = lbstokg( lbs); return kilograms;
2. This statement
2 [Link] statement in
in main() causes lbstokg() causes
the Return value the return value to
to be assigned to be assigned to this
this variable variable
i bl
repchar()
main()
kgs Kilograms
----------- -----------
----------- 74.84 -74.84--
----------- -----------
Reference Arguments
• A reference provides an alias – a different name –
for a variable
• Passing arguments by value is useful when the
function does not to modify the original variable in
th calling
the lli program.
• It offers insurance that the function cannot harm the
original
i i l variable
i bl
• Passing arguments by reference uses a different
mechanism Instead of a value being passed to the
mechanism.
function , a reference to the original variable , in the
calling program is passed
Reference Arguments
• An important advantage of passing by
reference is that the function can access the
actual variable in the calling program.
• Among other benefits
benefits, this provides a
mechanism for passing more than one value
from the function back to the calling program
Referencing: Creating Aliases
#include <iostream.h>

int main()
{
int x = 3;;
int &y = x;
cout<<"x= "<<x<<endl<<"y= "<<y<<endl;
y=7;
7
cout<<"x= "<<x<<endl<<"y= "<<y<<endl;
x 33;
x=33;
cout<<"x= "<<x<<endl<<"y= "<<y<<endl;
return 0;
}
Referencing : Example
// comparing pass by value and pass by reference int squareByValue(int a)
#include <iostream>
using namespace std; {
return a *=a;
=a;
int squareByValue(int);
void squareByReference(int&);
}

int main() void squareByReference (int


{ & )
&y)
int x = 2, z = 4; {
cout << "x = "<<x<< " before squareByValue\n" y *=y;
<<"Value returned by squareByValue: " }
<< squareByValue(x)<<endl
<<"x= "<<x<< " after squareByValue\n"<<endl;
x = 2 before squareByValue
cout <<"z = "<<z<< " before
Value returned by squareByValue: 4
squreByReference"<< endl; x= 2 after squareByValue
squareByReference(z);
cout << "z = " << z << " after z = 4 before squreByReference
squareByReference" << endl;
squareByReference
z = 16 after squareByReference
return 0;
}
Passing Simple Data types by Reference
// [Link]
// demonstrates passing by reference
#include <iostream>
using
i namespace std; d
int main()
{
void intfrac(float,
intfrac(float float&
float&, float&); //declaration
float number, intpart, fracpart; //float variables
do {
cout << "\nEnter
\nEnter a real number: ";; //number from user
cin >> number;
intfrac(number, intpart, fracpart); //find int and frac
cout << "Integerg part
p is " << intpart
p //print
p them
<< " fraction part is " << fracpart << endl;
} while ( number != 0.0 ); //exit loop on 0.0
return 0;
}
Passing Simple Data types by Reference
//.....................................................
// intfrac()
// fi
finds
d integer
i t and d fractional
f ti l parts
t off reall number
b
void intfrac(float n, float& intp, float& fracp)
{
long temp = static_cast<long> (n); // convert to long,
intp = static_cast<float> (temp); //back to float
fracp = n - intp; //subtract integer part
}
Passing Simple Data types by Reference
• The program will separate this number into an
integer and a fractional part i.e the user number
is 12.456 the program should report that the
integer part is 12.0 and the fractional part is
0 456
0.456
• Library function fmod() performs the similar
tasks for type double
double.
Passing Simple Data types by Reference
Intfrac(number,intpart,fracpart);
This statement in main() causes this
variable to be copied into this parameter
it also sets up aliases for these variables
with these names

main() Intfrac()

number n

intpart i t
intp

fracpart p
fracp

Fracp=n-intp;
Fracp=n intp;
These statements in intfrac() Long temp = static_cast<long>(n);
operate on these variable as if
they were in intfrac()
A More Complex Pass by Reference
// [Link]
// orders two arguments passed by reference
#include <iostream>
using namespace std;
int main()
{
void order(int&, int&); //prototype
int n1=99, n2=11; //this pair not ordered
int n3=22,, n4=88;; //this p
pair ordered
order(n1, n2); //order each pair of numbers
order(n3, n4);
cout << "n1=" << n1 << endl;; //print
p out all numbers
cout << "n2=" << n2 << endl;
cout << "n3=" << n3 << endl;
cout << "n4=" << n4 << endl;;
return 0;
}
A More Complex Pass by Reference
//.........................................
void order(int& numb1, int& numb2) //if 1st larger than 2nd,
{
if (numb1>numb2)
{
i t temp
int t = numb1; b1 //
//swap th
them
numb1 = numb2;
numb2 = temp;
}
}
Function Overloading
• A C++ programmer
g mayy use the same
name for more than one function.
• This would typically be done for different
but related functions that perform similar
tasks.
tasks
• Function overloading defines a new
meaning for a function name that is
already in use.
Function Overloading Contd..
Contd
• These two functions are different, even
though they have the same name

int sqrt (int x)


{
….
}

double sqrt (double x)


{
….
}
Function Overloading Contd..
Contd
• In C++, when the compiler sees a function
call, it selects one from its list of known
functions by y examiningg both the called
function name and the arguments provided
in the call.
• When an overloaded function is called the
compiler selects the proper function by
examining the number, types and order of
the arguments in the call.
Function Overloading Contd..
Contd
• Function Signature
– The combination of a function's name and its
parameter list is called its signature. Every
function must have a unique signature
– Overloaded functions ((functions with same
name) can have different return types but
must have different parameter list.
Examples : Function Overloading
// some function prototypes
y
void fun (void);
int fun (int); // valid overloading
double fun (int, int) // valid overloading
double fun (int); // illegal redefinition
int fun (void); // illegal redefinition
Function Overloading Example
// [Link]
// demonstrates function overloading
#include <iostream>
iostream
using namespace std;

void repchar(); //declarations


void repchar(char);
void repchar(char, int);

int main()
{
repchar();
repchar( '=' );
repchar( '+'
'+', 30);
return 0;
}
Function Overloading Example
//...................................
// repchar()
// displays 45 astericks
void repchar()
{
for(int jj=0; 0; j<45; j++) //always loops 45 times
cout << '*' ; //always prints astericks
cout << endl;
}
//..................................
// repchar()
// displays 45 copies of specified character
void repchar (char ch)
{
for (int j=0; j<45; j++) // always loops 45 times
coutt << ch; h // prints
i t specified
ifi d character
h t
cout << endl;
}
//...................................
// repchar()
p ()
// displays specified number of copies of specified character
void repchar(char ch, int n)
{
for(int jj=0;
0; j<n;
j n; jj++)) // loops n times
cout << ch; //prints specified character
cout << endl;
}
RECURSION
• Existence of functions makes ppossible a
programming technique called recursion
• Recursion involves a function calling
itself
• Recursion is much easier to understand
with an example
p than with lengthy
g y
explanations
RECURSION EXAMPLE
//[Link]
//calculate factorials using recursion
#include<iostream>
using namespace std;
unsigned long factfunc(unsigned long); //declaration
i t main()
int i ()
{
int n;
unsigned long fact; //factorial
cout<<"Enter an integer : ";
cin>>n;
fact=factfunc(n);
cout<<"Factorial of " <<n <<" is " <<fact <<endl;
return
t 0
0;
}
RECURSION EXAMPLE
//..........................
//factfunc()
//calls itself to calculate factorial
unsigned long factfunc(unsigned long n)
{
if (n>1)
return n n*factfunc(n-1);
factfunc(n 1); //self call
else
return 1;
}
Inline Functions
• To save execution time in short functions
• At a function call in the source file the
actual code is inserted, instead of jump
to the function
• Inline library functions are usually defined
(not just declared) in header files
INLINE FUNCTION EXAMPLE
//[Link]
//demonstrate inline function
#include<iostream>
using namespace std;
//lbstokg()
//converts pound to kilograms
inline float lbstokg(float pounds)
{
return 0.453592*pounds;
}
//.........................
int main()
{
float lbs;
cout<<"\nEnter
t "\ E t your weight i ht in
i pounds:
d ";"
cin>>lbs;
cout<<"Your weight in kilogram is " <<lbstokg(lbs)<<endl;
return 0;;
}
Default Argument
• A function can be called without specifying all
g
its argument
• Default argument is useful if you don’t want
to go to the trouble of writing arguments ii.e.
e
almost always have the same value
• Using default arguments means that the
existing function calls can continue to use the
old number of arguments while new functions
calls can use more
Default Argument Example
//[Link] //.............................
//demonstrate missing and default argument //repcahr()
#include<iostream> //
//display line off characters
void repchar(char ch, int n)
using namespace std; {
void repchar(char='*',int=45);
( ) for (int jj=0;j<n
0;j n ; jj++))
int main() cout <<ch;
{ cout <<endl;
repchar();
p () }
repchar('=');
repchar('+',30);
return 0;;
}
Variables and Storage Classes
• Storage Class of a variable
– It determines which part of the program
can access it and how long g it stays
y in
existence
• Three storage classes
– Automatic or Local Variables
– External
E t l or Global
Gl b l V
Variables
i bl
– Static Local Variables
Automatic Variables or Local Variables
• Variables defined within a function body
• Sometime auto keyword is used
• Lifetime
– Variable is not created until the function in which it is defined
is called
– When called function returns and control passed to the
calling program, the variables are destroyed and their value
is lost
• Visibility or Scope
– Location within a program from which it can be accessed
(With in a function )
• Initialization
– When variable is created it is not initialized by compiler
External or Global Variables
• Variables defined outside a function body
y
• Lifetime
– Exists for the life of the program
• Visibility or Scope
– Visible to all the functions that follow the
definition in a program
• Initialization
– When variable is created it is automatically
initialized to 0
Example : Global Variables
// [Link] //..............
// demonstrates global variables void g getachar()
()
#include<iostream> {
#include<conio.h> ch=getch();
using namespace std; }
char ch = 'a'; //global variable //..............
void getachar(); void putachar()
void putachar(); {
int main() cout<<ch;
{ }
while(ch != '\r')
{
getachar();
putachar();
}
cout<<endl;
return 0;
}
Static Local Variables
• Lifetime
– Created on first call of the function and exists
for the life of the program
• Visibility or Scope
– Visible within the function
• Initialization
– Initialized only once per program
Example : Static Local Variable
// [Link]
// Demonstrates static variables
#include<iostream>
using namespace std;
float getavg(float);
//--------------------------------------------------------------
int main() // getavg()
{ // finds average g of old plusp new data
float data=1, avg; float getavg(float newdata)
{
while( data != 0 ) static float total = 0; //static variables are initialized
{ static int count = 0; // only y once p per pprogram
g
cout << "Enter a number: "; count++; //increment count
cin >> data; total += newdata; //add new data to total
avg = getavg(data); return total / count; //return the new average
cout << "New
New average is " }
<< avg << endl;
}
return 0;
}
#include<iostream> Variable Storage Classes
using namespace std;

void a(void); //function declarations


Another Example
void b(void);
void c(void);
int x = 1; //global variable
int main()
{
int x = 5; //local variable to main

cout << "local x in outer scope of main is "<<x<<endl;


{ // starting a new scope
int x = 7;
cout << "local
local x is in inner scope of main is "<<x<<endl;
<<x<<endl;
} //end of inner or new scope
cout << "local x in outer scope of main is "<<x<<endl;
a(); //func a has automatic local x
b(); //func b has static local x
c(); //func c uses a global x
a(); //func a reinitializes automatic local x
b(); //static local x retains its previous value
c(); //global x also retains its value
cout << "local x in main is "<<x<<endl;
return 0;
} Contd’
Variable Storage Classes
void a(void)
{
( ) Another Example..Contd
int x = 25; //initialized each time a is called
cout<<endl<<"local x in a is "<<x<<" after entering a"<<endl;
++x;
cout<<"local x in a is "<<x<<" before exiting a"<<endl;
}
void b(void)
{
static int x = 50; //intialization only first time
//b is called
cout<<endl<<"local staic x is "<<x<<" on entering b"<<endl;
++x;
cout<<"local static x is "<<x<<" on exiting b"<<endl;
}
void c(void)
{
g
cout<<endl<<"global x is "<<x<<" on entering
g c"<<endl;;
x *= 10;
cout <<"global x is "<<x<<" on exiting c"<<endl;
}
THE END

You might also like