0% found this document useful (0 votes)
15 views15 pages

Unit-4.2, Notes

The document discusses C++ functions including user-defined and library functions. It describes how functions are declared, defined, called, and passed parameters by value or reference. Inline functions are also covered, explaining how they reduce function call overhead by expanding the function body at the call site instead of performing a function switch.

Uploaded by

Ritiesh Bhatia
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)
15 views15 pages

Unit-4.2, Notes

The document discusses C++ functions including user-defined and library functions. It describes how functions are declared, defined, called, and passed parameters by value or reference. Inline functions are also covered, explaining how they reduce function call overhead by expanding the function body at the call site instead of performing a function switch.

Uploaded by

Ritiesh Bhatia
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/ 15

C++ functions

A function is a block of code that performs a speci c task. Dividing a


complex problem into smaller chunks makes our program easy to
understand and reusable.
There are two types of function:
1. Standard Library Functions: Prede ned in C++
2. User-de ned Function: Created by users

Simple functions
C++ User-de ned Function
C++ allows the programmer to de ne their own function.
A user-de ned function groups code to perform a speci c task and that
group of code is given a name (identi er).
When the function is invoked from any part of the program, it all executes the
codes de ned in the body of the function.

C++ Function Declaration

The syntax to declare a function is:


returnType functionName (parameter1, parameter2,...) {
// function body
}

Example:
// function declaration
void greet() {
cout << "Hello World";
}
Function Call
int main() {

// calling a function
greet();

It's also possible to return a value from a function. For this, we need to
specify the returnType of the function during function declaration.
Then, the return statement can be used to return a value from a function.

For example,
fi
fi
fi
fi
fi
fi
fi
fi
fi
int add (int a, int b) {
return (a + b);
}

The code return (a + b); returns the sum of the two parameters as the
function value.
The return statement denotes that the function has ended. Any code after
return inside the function is not executed.

Function Prototype
In C++, the code of function declaration should be before the function call.
However, if we want to de ne a function after the function call, we need to
use the function prototype. This provides the compiler with information about
the function name and its parameters. That's why we can use the code to
call a function before the function has been de ned.

The syntax of a function prototype is:


returnType functionName(dataType1, dataType2, …);

Bene ts of Using User-De ned Functions


• Functions make the code reusable. We can declare them once and use
them multiple times.
• Functions make the program easier as each small task is divided into a
function.
• Functions increase readability.

C++ Library Functions


Library functions are the built-in functions in C++ programming.

Programmers can use library functions by invoking the functions directly;


they don't need to write the functions themselves.

Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
In order to use library functions, we usually need to include the header le
in which these library functions are de ned.

For instance, in order to use mathematical functions such as sqrt() and


abs(), we need to include the header le cmath.
fi
fi
fi
fi
fi
fi
fi
Call and return by reference
There are two ways to pass value or data to function in C++ language:
1. call by value and
2. call by reference.
Original value is not modi ed in call by value but it is modi ed in call by
reference.

Call by value in C++


In call by value, original value is not modi ed.

In call by value, value being passed to the function is locally stored by the
function parameter in stack memory location. If you change the value of
function parameter, it is changed for the current function only. It will not
change the value of variable inside the caller method such as main().

#include <iostream>
using namespace std;
void change(int data);
int main()
{
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data)
{
data = 5;
}

OUTPUT: Value of the data is: 3

Call by reference in C++


In call by reference, original value is modi ed because we pass reference
(address).

Here, address of the value is passed in the function, so actual and formal
arguments share the same address space. Hence, value changed inside the
function, is re ected inside as well as outside the function.

EXAMPLE:

#include<iostream>
using namespace std;
fl
fi
fi
fi
fi
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
return 0;
}
Output:

Value of x is: 100


Value of y is: 500

Di erence between call by value and call by reference in C++

N Call by value Call by reference


o
.

1 A copy of value is passed to An address of value is


the function passed to the function

2 Changes made inside the Changes made inside the


function is not re ected on function is re ected outside
other functions the function also

3 Actual and formal arguments Actual and formal arguments


will be created in di erent will be created in same
memory location memory location
ff
fl
fl
ff
Inline Functions
Inline function is one of the important feature of C++.

When the program executes the function call instruction the CPU stores
the memory address of the instruction following the function call, copies
the arguments of the function on the stack and nally transfers control to
the speci ed function.
The CPU then executes the function code, stores the function return value
in a prede ned memory location/register and returns control to the calling
function.
This can become overhead if the execution time of function is less than the
switching time from the caller function to called function (callee).
For functions that are large and/or perform complex tasks, the overhead of
the function call is usually insigni cant compared to the amount of time the
function takes to run. However, for small, commonly-used functions, the
time needed to make the function call is often a lot more than the time
needed to actually execute the function’s code.
This overhead occurs for small functions because execution time of small
function is less than the switching time.

C++ provides an inline functions to reduce the function call overhead.

Inline function is a function that is expanded in line when it is called. When


the inline function is called whole code of the inline function gets inserted
or substituted at the point of inline function call.
This substitution is performed by the C++ compiler at compile time.
Inline function may increase e ciency if it is small.

The syntax for de ning the function inline is:


inline return-type function-name(parameters)
{
// function code
}

Compiler can ignore the request for inlining. Compiler may not perform
inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)

2) If a function contains static variables.

3) If a function is recursive.
fi
fi
fi
ffi
fi
fi
4) If a function return type is other than void, and the return statement
doesn’t exist in function body.

5) If a function contains switch or goto statement.

Inline functions provide following advantages:


1) Function call overhead doesn’t occur.

2) It also saves the overhead of push/pop variables on the stack when


function is called.

3) It also saves overhead of a return call from a function.

4) When you inline a function, you may enable compiler to perform context
speci c optimization on the body of function. Such optimizations are not
possible for normal function calls. Other optimizations can be obtained by
considering the ows of calling context and the called context.

5) Inline function may be useful (if it is small) for embedded systems


because inline can yield less code than the function call preamble and
return.

Inline function disadvantages:


1) The added variables from the inlined function consumes additional
registers, After in-lining function if variables number which are going to use
register increases than they may create overhead on register variable
resource utilization. This means that when inline function body is
substituted at the point of function call, total number of variables used by
the function also gets inserted. So the number of register going to be used
for the variables will also get increased. So if after function inlining variable
numbers increase drastically then it would surely cause an overhead on
register utilization.

2) If you use too many inline functions then the size of the binary
executable le will be large, because of the duplication of same code.

3) Too much inlining can also reduce your instruction cache hit rate, thus
reducing the speed of instruction fetch from that of cache memory to that
of primary memory.

4) Inline function may increase compile time overhead if someone changes


the code inside the inline function then all the calling location has to be
recompiled because compiler would require to replace all the code once
again to re ect the changes, otherwise it will continue with old
functionality.
fi
fl
fi
fl
5) Inline functions may not be useful for many embedded systems.
Because in embedded systems code size is more important than speed.

6) Inline functions might cause thrashing because inlining might increase


size of the binary executable le. Thrashing in memory causes
performance of computer to degrade.

Example:
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
} //

Output: The cube of 3 is: 27

Di erence between macros and inline functions.

S.No Inline Macro

1 An inline function is de ned by the Whereas the macros are de ned by


inline keyword. the #de ne keyword.

2 Through inline function, the class’s Whereas macro can’t access the
data members can be accessed. class’s data members.

3 In the case of inline function, the Whereas in the case of macros, the
program can be easily debugged. program can’t be easily debugged.

4 In the case of inline, the arguments Whereas in the case of macro, the
are evaluated only once. arguments are evaluated every time
whenever macro is used in the
program.
ff
fi
fi
fi
fi
5 In C++, inline may be de ned either Whereas the macro is all the time
inside the class or outside the class. de ned at the beginning of the
program.

6 In C++, inside the class, the short While the macro is speci cally
length functions are automatically de ned.
made the inline functions.

7 Inline is not as widely used as macros. While the macro is widely used.

8 Inline is not used in competitive While the macro is very much used
programming. in competitive programming.

9 Inline function is terminated by the While the macro is not terminated by


curly brace at the end. any symbol, it is terminated by a new
line.

FUNCTION OVERLOADING

Function overloading is a feature of object oriented programming where


two or more functions can have the same name but di erent parameters.

When a function name is overloaded with di erent jobs it is called Function


Overloading.

In Function Overloading “Function” name should be the same and the


arguments should be di erent.
Function overloading can be considered as an example of polymorphism
feature in C++
Example:
#include <iostream>
using namespace std;

void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is oat " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
fi
fi
fl
fi
fi
ff
ff
ff
}

int main() {
print(10);
print(10.10);
print("ten");
return 0;
}
Output:
Here is int 10
Here is oat 10.1
Here is char* ten

How Function Overloading works?

1. Exact match:- (Function name and Parameter)

2. If a not exact match is found:–


->Char, Unsigned char, and short are promoted to an int.
->Float is promoted to double

3. If no match found:
->C++ tries to nd a match through the standard conversion.
ELSE ERROR

Default arguments in C++


A default argument is a value provided in a function declaration that is
automatically assigned by the compiler if the caller of the function doesn’t
provide a value for the argument with a default value. In case any value is
passed the default value is overridden.
Example:
#include <iostream>
using namespace std;

// A function with default arguments,


// it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0)
{
return (x + y + z + w);
}

// Driver Code
int main()
fl
fi
{
// Statement 1
cout << sum(10, 15) << endl;

// Statement 2
cout << sum(10, 15, 25) << endl;

// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Output:
25
50
80

When Function overloading is done along with default values. Then we


need to make sure it will not be ambiguous.
The compiler will throw an error, if ambiguous. Following is the modi ed
version of above program,
#include <iostream>
using namespace std;

// A function with default arguments, it can be called with


// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0)
{
return (x + y + z + w);
}
int sum(int x, int y, oat z = 0, oat w = 0)
{
return (x + y + z + w);
}
// Driver Code
int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}

OUTPUT: ERROR
fl
fl
fi
Default arguments are di erent from constant arguments as constant
arguments can’t be changed whereas default arguments can be
overwritten if required.

Default arguments are overwritten when calling function provides values for
them. For example, calling of function sum(10, 15, 25, 30) overwrites the
value of z and w to 25 and 30 respectively.

During the calling of function, arguments from calling function to called


function are copied from left to right. Therefore, sum(10, 15, 25) will assign
10, 15, and 25 to x, y, and z. Therefore, the default value is used for w only.

Once the default value is used for an argument in the function de nition, all
subsequent arguments to it must have a default value. It can also be stated
as default arguments are assigned from right to left. For example, the
following function de nition is invalid as the subsequent argument of
default variable z is not default.
fi
ff
fi
FRIEND FUNCTIONS
Friend functions of the class are granted permission to access private and
protected members of the class in C++. They are de ned globally outside
the class scope. Friend functions are not member functions of the class.

A friend function is a function that is declared outside a class but is


capable of accessing the private and protected members of the class.

There could be situations in programming wherein we want two classes to


share their members. These members may be data members, class
functions or function templates. In such cases, we make the desired
function, a friend to both these classes which will allow accessing private
and protected data members of the class.

The friend function is declared using the friend keyword inside the body of
the class.

Friend Function Syntax:


1 class className {
2 ... .. ...
3 friend returnType functionName(arguments);
4 ... .. ...
5}
By using the keyword, the ‘friend’ compiler understands that the given
function is a friend function.

We declare friend function inside the body of a class, whose private and
protective data needs to be accessed, starting with the keyword friend to
access the data. We use them when we need to operate between two
di erent classes at the same time.

Friend function is called as function_name(class_name) and member


function is called as class_name. function_name.

Use of Friend function in C++


We require friend functions whenever we have to access the private or
protected members of a class. This is only the case when we do not want
to use the objects of that class to access these private or protected
members.
ff
fi
Characteristics of Friend Function in C++
• The function is not in the ‘scope’ of the class to which it has been
declared a friend.

• Friend functionality is not restricted to only one class

• Friend functions can be a member of a class or a function that is declared


outside the scope of class.

• It cannot be invoked using the object as it is not in the scope of that


class.

• We can invoke it like any normal function of the class.

• Friend functions have objects as arguments.

• It cannot access the member names directly and has to use dot
membership operator and use an object name with the member name.

• We can declare it either in the ‘public’ or the ‘private’ part.

Implementing Friend Functions


Friend Functions can be implemented in two ways:

A method of another class: We


declare a friend class when we want to access
the non-public data members of a particular class.

A ‘global friend function’ allows you to access all the private


A Global function:
and protected members of the global class declaration.

Example: C++ friend function used to print the length of the


box.

#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box (): length (0) {}
friend int printLength (Box); //friend function
};
int printLength (Box b)
{
b. length +=10;
return b. length;
}
int main ()
{
Box b;
cout <<” Length of box:” <<printLength
(b)<<endl;
return 0;
}

Output:
Length of box:10

Example: when the function is friendly for two classes.

#include<iostream>
using namespace std;
class B; //forward declaration.
class A
{
int x;
public:
void setdata (int i)
{
x=i;
}
friend void max (A, B); //friend function.
} ;
class B
{
int y;
public:
void setdata (int i)
{
y=i;
}
friend void max (A, B);
};
void max (A a, B b)
{
if (a.x >= b.y)
std:: cout<< a.x << std::endl;
else
std::cout<< b.y << std::endl;
}
int main ()
{
A a;
B b;
a. setdata (10);
b. setdata (20);
max (a, b);
return 0;
}

Output:

20

You might also like