0% found this document useful (0 votes)
3 views19 pages

3 FunctionsC++

Uploaded by

vipin pal
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)
3 views19 pages

3 FunctionsC++

Uploaded by

vipin pal
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
You are on page 1/ 19

Functions in C++

Dr. Alekha Kumar Mishra


function

Function is a group of valid statements
combined together to perform a well defined
task

Components to add for a user defined-function
– The function declaration
– The calls to the function
– The function definition

Dr. Alekha Kumar Mishra


//demonstrates function call Function
example
#include <iostream>
using namespace std;

void repchar(char, int); //function declaration

int main() {
repchar('-', 43); //call to function
cout << "Data typ Range" << endl;
repchar('=', 23);
cout << "char -128 to 127" << endl;
cout << "short -32,768 to 32,767" << endl;
cout << "int System dependent" << endl;
cout << "double -2,147,483,648 to 2,147,483,647" << endl;
repchar('-', 43);
char chin; int nin;
cout << "Enter a character: ";
cin >> chin;
cout << "Enter number of times to repeat it: ";
void repchar(char ch, int n) {
cin >> nin;
for(int j=0; j<n; j++)
repchar(chin, nin);
cout << ch;
return 0;
cout << endl;
}
}
3

Dr. Alekha Kumar Mishra


Pass by value

When constants or variables are passed to it,
the function creates new variables to hold the
values of these variable arguments.

The function gives these new variables the
names and data types of the parameters
specified in the declarator:
– In example : ch of type char and n of type int.

Passing arguments in this way, where the
function creates copies of the arguments
passed to it, is called passing by value.
4

Dr. Alekha Kumar Mishra


// demonstrates passing and returning a
structure
Passing a
#include <iostream>
using namespace std;
structure
struct Distance {
variable
int feet;
float inches; // adds two structures of type Distance, returns
}; sum
Distance addDist( Distance dd1, Distance
Distance addDist(Distance, Distance); dd2 ) {
void dispDist(Distance); Distance dd3;
dd3.inches = dd1.inches + dd2.inches;
int main() { dd3.feet = 0;
Distance d1, d2, d3; if(dd3.inches >= 12.0) {
cout << “\nEnter feet: “; cin >> d1.feet; dd3.inches -= 12.0; //by 12.0 and
cout << “Enter inches: “; cin >> d1.inches; dd3.feet++; //increase feet
}
cout << “\nEnter feet: “; cin >> d2.feet; dd3.feet += dd1.feet + dd2.feet; //add the
cout << “Enter inches: “; cin >> d2.inches; feet
d3 = addDist(d1, d2); return dd3; //return structure
cout << endl; }
dispDist(d1); cout << “ + “;
dispDist(d2); cout << “ = “;
dispDist(d3); cout << endl; void dispDist( Distance dd ) {
return 0; cout << dd.feet << “\’-” << dd.inches << “\””;
5
} }
Dr. Alekha Kumar Mishra
Reference Arguments

Passing arguments by value is useful when the function does
not need to modify the original variable in the calling program.

In passing arguments by reference, a reference to the original
variable in the calling program is passed.

An important advantage of passing by reference is that the
function can access the actual variables in the calling
program.

Among other benefits, this provides a mechanism for passing
more than one value from the function back to the calling
program.

Dr. Alekha Kumar Mishra


Example
// demonstrates passing by reference
#include <iostream>
using namespace std;
int main() {
void intfrac(float, float&, float&); //declaration
float number, intpart, fracpart; //float variables
do {
cout << “\nEnter a real number: “;
cin >> number;
intfrac(number, intpart, fracpart);
cout << “Integer part is “ << intpart
<< “, fraction part is “ << fracpart << endl;
} while( number != 0.0 );
return 0;
}

// finds integer and fractional parts of real number


void intfrac(float n, float& intp, float& fracp) {
long temp = static_cast<long>(n);
intp = static_cast<float>(temp);
fracp = n - intp; 7
}
Dr. Alekha Kumar Mishra
Default arguments

Parameters can be assigned default values.

Parameters assume their default values when no
actual parameters are specified for them in a
function call.

A default argument is type checked at the time of
function declaration and evaluated at the time of
call

Default arguments may be provided for trailing
arguments only

Dr. Alekha Kumar Mishra


Example: default arguments
// Find the sum of numbers in a range of values between “lower” and “upper”
using increment “inc”
int sum(int lower,int upper=100,int inc=1){
int sum=0;
for(int k=lower; k<=upper; k+= inc)
sum += k;
return sum;
}
Int main(){
cout<<sum(1);
cout<<sum(1, 10);
cout<<sum(1, 10, 2);
return 0;
} 9

Dr. Alekha Kumar Mishra


recursion

Recursion involves a function calling itself.

Recursion is much easier to understand with an example than with
lengthy explanations

Each version of the recursive function stores its own value of
variables while it’s busy calling another version of itself.

When a recursive function completes its execution, it returns to the
previously called version of itself

Every recursive function must be provided with a way to end the
recursion. Otherwise it will call itself forever and crash the
program.

It is not true that many versions of a recursive function are stored
in memory while it’s calling itself. Each version’s variables are
stored, but there’s only one copy of the function’s code.
10

Dr. Alekha Kumar Mishra


Inline function

While a function may help to save memory
space, its call and return process requires some
extra time.

There must be an instruction
– for the jump to the function instructions
– for pushing arguments onto the stack and removing
them,
– for restoring registers
– to return to the calling program and dealing with
return values

All these instructions slow down the program.
11

Dr. Alekha Kumar Mishra


Inline function

Making a short section of code into a function
may impose penalty just as much as a larger
function.

One solution is to simply repeat the necessary
code in your program

However, the repeated code lose the benefits
of program organization and clarity.

The solution to this issue is the inline function.

12

Dr. Alekha Kumar Mishra


Inline function

Inline functions is a normal function in the source
file but compiles into inline code instead of into a
function.

The function is shown as a separate entity.

However, when the program is compiled, the
inline function is actually inserted into the
program wherever a function call occurs.

Functions that are very short, say one or two
statements, are candidates to be inlined

13

Dr. Alekha Kumar Mishra


Elements violating inline property

A recursive call to the function

A loop inside function

Functions whose address is referenced
somewhere

Virtual functions (there are some exceptions)

A large number of statements

The last case does not generate any error.
Nevertheless, the inline property is violated

14

Dr. Alekha Kumar Mishra


Example
// demonstrates inline functions
#include <iostream>
using namespace std;

inline float lbstokg(float pounds) {


return 0.453592 * pounds;
}

int main() {
float lbs;
cout << “\nEnter your weight in pounds: “;
cin >> lbs;
cout << “Your weight in kilograms is “ << lbstokg(lbs) << endl;
return 0;
}
15

Dr. Alekha Kumar Mishra


Function Calls on the
Left of the Equal Sign

A function that returns a reference, on the other hand, is
treated as if it were a variable.

It returns an alias to a variable, namely the variable in the
function’s return statement.

Thus it can be used on the left side of an equal sign
int main() {
int i=2,j=3;
max(i,j)= -30;
cout<<“i=“<< i << ‘\t’ <<“j=“ << j << ‘\t’ <<endl;
}
int& max(int &x, int &y){
return x>y ? x:y;
}

16

Dr. Alekha Kumar Mishra


Function overloading

We can use same function name to create funcions that
perform a variety of different task

Also called function polymorphism

An overloaded function appears to perform different
activities depending on the kind of data sent to it.

It performs one operation on one kind of data but another
operation on a different kind.

Two variations
– Function overloaded with different number of arguments
– Function overloaded with different kind of arguments

17

Dr. Alekha Kumar Mishra


// demonstrates function Function
overloading
#include <iostream> Overloading with
using namespace std; Different Numbers
void repchar();
void repchar(char);
of Arguments
void repchar(char, int); // repchar() : displays 45 copies of specified
character
int main() { void repchar(char ch) {
repchar(); for(int j=0; j<45; j++) // always loops 45
repchar(‘=’); times
repchar(‘+’, 30); cout << ch;
return 0; cout << endl;
} }
// repchar() : displays specified number of
// repchar() : displays 45 copies
asterisks // of specified character
void repchar() { void repchar(char ch, int n) {
for(int j=0; j<45; j++) for(int j=0; j<n; j++)
cout << ‘*’; cout << ch;
cout << endl; cout << endl;
} } 18

Dr. Alekha Kumar Mishra


Function Overloading with
// demonstrates overloaded functions Different types of
#include <iostream>
using namespace std; Arguments
struct Distance { int main() {
int feet; Distance d1;
float inches; float d2;
}; cout << “\nEnter feet: “;
cin >> d1.feet;
void dispDist( Distance dd ) { cout << “Enter inches: “;
cout << dd.feet << “\’-” << dd.inches cin >> d1.inches;
<< “\””; cout << “Enter entire distance
} in inches: “;
cin >> d2;
void dispDist( float dd ) { cout << “\nd1 = “;
int feet = static_cast<int>(dd / 12); dispDist(d1);
float inches = dd - feet*12; cout << “\nd2 = “;
cout << feet << “\’-” << inches << “\””; dispDist(d2);
} cout << endl;
return 0;
} 19

Dr. Alekha Kumar Mishra

You might also like