0% found this document useful (0 votes)
2 views

Unit 4 Functions (1)

Unit 4 discusses various aspects of functions in C++, including their definition, types (standard library and user-defined), and how to declare, call, and pass arguments to them. It covers advanced topics such as call by value, call by reference, return by reference, inline functions, function overloading, and default arguments. The document provides examples and explanations to illustrate these concepts.

Uploaded by

23it062
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit 4 Functions (1)

Unit 4 discusses various aspects of functions in C++, including their definition, types (standard library and user-defined), and how to declare, call, and pass arguments to them. It covers advanced topics such as call by value, call by reference, return by reference, inline functions, function overloading, and default arguments. The document provides examples and explanations to illustrate these concepts.

Uploaded by

23it062
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Unit 4 Functions

 simple functions
 call by reference
 return by reference
 Inline functions
 overloaded functions
 default arguments
A function is a block of code that performs a specific task. A function
is a group of statements that together perform a task. Every C++
program has at least one function, which is main(), and all the most
trivial programs can define additional functions.
A function is known with various names like a method or a sub-routine
or a procedure etc.
There are two types of function:
 Standard Library Functions: Predefined in C++
 User-defined Function: Created by users

Defining a Function
The general form of a C++ function definition is as follows −

return_type function_name( parameter list )


{
body of the function
}

A C++ function definition consists of a function header and a function


body. Here are all the parts of a function −

Return Type − A function may return a value. The return_type is the


data type of the value the function returns. Some functions perform the
desired operations without returning a value. In this case, the
return_type is the keyword void.

Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.

Function Body − The function body contains a collection of statements


that define what the function does.

Function Declarations
A function declaration tells the compiler about a function name and
how to call the function. The actual body of the function can be defined
separately.
A function declaration has the following parts −
return_type function_name( parameter list );

Calling a Function
While creating a C++ function, you give a definition of what the
function has to do. To use a function, you will have to call or invoke
that function.
When a program calls a function, program control is transferred to the
called function. A called function performs defined task and when it’s
return statement is executed or when its function-ending closing brace
is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters
along with function name, and if function returns a value, then you can
store returned value.
Example: -
#include <iostream>
using namespace std;

// function declaration
int max(int num1, int num2);

int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;

// calling a function to get max value.


ret = max(a, b);
cout << "Max value is : " << ret << endl;

return 0;
}

// function returning the max between two numbers


int max(int num1, int num2)
{
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
Function Arguments
If a function is to use arguments, it must declare variables that accept the values
of the arguments. These variables are called the formal parameters of the
function.
The formal parameters behave like other local variables inside the function and
are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a
function.
Sr.No Call Type & Description

1 Call by Value

This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect
on the argument.

2 Call by Reference
This method copies the reference of an argument into the formal parameter. Inside the
function, the reference is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.

No. Call by value Call by reference

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


function

2 Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected outside the function also

3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location

Call by value Call by reference


#include <iostream> #include<iostream>
using namespace std; using namespace std;
void change(int data); void swap(int *x, int *y)
int main() {
{ int swap;
int data = 3; swap=*x;
change(data); *x=*y;
cout << "Value of the data is: " << data<< *y=swap;
endl; }
return 0; int main()
} {
void change(int data) int x=500, y=100;
{ swap(&x, &y); // passing value to function
data = 5; cout<<"Value of x is: "<<x<<endl;
} cout<<"Value of y is: "<<y<<endl;
return 0;
}
Return by reference
In C++ Programming, not only you pass values by reference to a function but
you can also return a value by reference.
#include <iostream>
using namespace std;
// global variable
int num;
// function declaration
int& test();
int main()
{
// assign 5 to num variable
// equivalent to num = 5;
test() = 5;
cout << num;
return 0;
}
// function definition
// returns the address of num variable
int& test()
{
return num;
}
In program above, the return type of function test() is int&. Hence, this function
returns a reference of the variable num. The return statement is return num;.
Unlike return by value, this statement doesn't return value of num, instead it
returns the variable itself (address).So, when the variable is returned, it can be
assigned a value as done in test() = 5;This stores 5 to the variable num, which is
displayed onto the screen.
Inline functions
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 finally transfers control to the specified
function. The CPU then executes the function code, stores the function return
value in a predefined 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 insignificant 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 efficiency if it is small.
The syntax for defining the function inline is:
inline return-type function-name(parameters)
{
// function code
}
Remember, inlining is only a request to the compiler, not a command. 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.
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
specific optimization on the body of function. Such optimizations are not
possible for normal function calls. Other optimizations can be obtained by
considering the flows 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 file
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 reflect the
changes, otherwise it will continue with old functionality.
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 file. 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

Example:

#include <iostream>

using namespace std;

inline int Max(int x, int y)

return (x > y)? x : y;

// Main function for the program

int main() {

cout << "Max (20,10): " << Max(20,10) << endl;

cout << "Max (0,200): " << Max(0,200) << endl;

cout << "Max (100,1010): " << Max(100,1010) << endl;

return 0;

}
Overloaded functions
Function overloading is a feature of object oriented programming where two or
more functions can have the same name but different parameters.

When a function name is overloaded with different jobs it is called Function


Overloading.

In Function Overloading “Function” name should be the same and the arguments
should be different.
Function overloading can be considered as an example of polymorphism feature
in C++.
Following is a simple C++ example to demonstrate function overloading.
#include <iostream>
using namespace std;
void print(int i)
{
cout << " Here is int " << i << endl;
}
void print(double f)
{
cout << " Here is float " << f << endl;
}
void print(char const *c)
{
cout << " Here is char* " << c << endl;
}

int main()
{
print(10);
print(10.10);
print("ten");
return 0;
}
Output:
Here is int 10
Here is float 10.1
Here is char* ten
Default arguments
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.

// CPP Program to demonstrate Default Arguments


#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()
{
// 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
References
https://www.geeksforgeeks.org/
https://www.programiz.com/
https://www.javatpoint.com/
https://www.w3schools.com/cpp/
https://www.codingninjas.com/

You might also like