SlideShare a Scribd company logo
1 of 73
Functions In C++
Presented by:
Mr. Sachin Sharma, Dr. Vinod Jain , Ms. Kriti Bansal
Assistant Professor, Dept. Of CE&A
GLA University, Mathura
Syllabus
4.0 Functions In C++
4.1 Call by Value & Reference
4.2 Inline Function
4.3 Default Arguments
4.4 Function Overloading.
<Subject Code> <Name of Subject> 2
Module 1- Section 4- Lecture 1
4.0 Functions In C++
4.0 Functions In C++
4.0 Functions In C++
• A function is a group of statements that together perform a task.
• Every C++ program has at least one function, which is main()
4.0 Functions In C++
A function declaration tells the compiler about a function's name,
return type, and parameters.
A function definition provides the actual body of the function.
Defining a Function
The general form of a C++ function definition is as follows −
return_type function_name( parameter list )
{
body of the function
}
4.0 Functions In C++ : Defining a Function
4.0 Functions In C++
• 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.
int fact(int no)
{
int i,f=1;
for(i=1;i<=no;i++)
f=f*i;
return(f);
}
4.0 Functions In C++
• Function Name −
• This is the actual name of the function.
• The function name and the parameter
list together constitute the function
signature.
• Example
• Here function name is fact
int fact(int no)
{
int i,f=1;
for(i=1;i<=no;i++)
f=f*i;
return(f);
}
4.0 Functions In C++
• Parameters −
• When a function is invoked, you pass a
value to the parameter.
• 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.
• Example (int no)
int fact(int no)
{
int i,f=1;
for(i=1;i<=no;i++)
f=f*i;
return(f);
}
4.0 Functions In C++
• Function Body −
• The function body contains a collection of
statements that define what the function
does.
• Example Function body here is
{
int i,f=1;
for(i=1;i<=no;i++)
f=f*i;
return(f);
}
int fact(int no)
{
int i,f=1;
for(i=1;i<=no;i++)
f=f*i;
return(f);
}
4.0 Functions In C++
• // A program to write and use a function to calculate factorial of a
number
4.0 Functions In C++
// A program to write and use a function to
// calculate factorial of a number
#include<iostream>
#include<conio.h>
using namespace std;
//function prototype
int fact(int);
//main function
int main()
{
int n,factorial;
cout<<"Enter the n : "<<endl;
cin>>n;
//calculate factorial using function.
factorial=fact(n);
//print factorial
cout<<"Factorial of "<<n<<" is "<<factorial;
return 0;
}
//function
int fact(int no)
{
int i,f=1;
for(i=1;i<=no;i++)
f=f*i;
return(f);
}
Output
Enter the no.
5
Factorial of 5 is 120
4.0 Functions In C++
• Parameter Passing to functions
1. Actual Parameters
2. Formal parameters
4.0 Functions In C++
• Parameter Passing to functions
Actual Parameters
• The parameters passed to function are called actual parameters.
• For example, in the above program 5 is actual parameters.
• Formal parameters
• The parameters received by function are called formal parameters.
• For example, in the above program no is a formal parameter.
Module 1- Section 4- Lecture 2
4.1 Call by Value & Reference
4.1 Call by Value & Reference
• There are two most popular ways to pass parameters.
1. Call by Value
2. Call by reference
4.1 Call by Value & Reference
• There are two most popular ways to pass parameters.
1. Call by Value
2. Call by reference
4.1 Call by Value & Reference
4.1 Call by Value
• Call by Value:
• In this parameter passing method, values of actual parameters are
copied to function’s formal parameters.
• The two types of parameters are stored in different memory
locations.
• So any changes made inside functions are not reflected in actual
parameters of caller.
4.1 Call by Value
• // Call by value
• #include <iostream>
• using namespace std;
•
• // function declaration
• void swap(int x, int y);
•
• int main () {
• // local variable declaration:
• int a = 100;
• int b = 200;
•
• cout << "Before swap, value of a :" << a << endl;
• cout << "Before swap, value of b :" << b << endl;
•
• // calling a function to swap the values.
• swap(a, b);
•
• cout << "After swap, value of a :" << a << endl;
• cout << "After swap, value of b :" << b << endl;
• return 0;
• }
• // function definition to swap the values.
• void swap(int x, int y) {
• int temp;
• temp = x;
• x = y;
• y = temp;
•
• return;
• }
• Output
• Before swap, value of a :100
• Before swap, value of b :200
• After swap, value of a :100
• After swap, value of b :200
4.1 Call by Reference
• call by reference
• The call by reference method of passing arguments to a function
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 passed
argument.
4.1 Call by Reference
• call by reference
• To pass the value by reference, argument reference is passed to the
functions just like any other value.
• So accordingly you need to declare the function parameters as
reference types as in the following function swap(), which exchanges
the values of the two integer variables pointed to by its arguments.
void swap(int &x, int &y)
{
}
4.1 Call by Reference
• Program to swap two numbers using call by reference
• Make a swap() function which pass parameters by reference
void swap(int &x, int &y) {
int temp;
temp = x;
x = y;
y = temp;
return;
}
4.1 Differnce between
Call by Value & Reference
Module 1- Section 4- Lecture 3
4.2 Inline Function
4.2 Inline Function
• The inline functions are a C++ enhancement feature to decrease the
execution time of a program.
• 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.
• Functions can be instructed to compiler to make them inline so that
compiler can replace those function definition wherever those are
being called.
4.2 Inline Function
4.2 Inline Function :
How to make function inline:
To make any function as inline, start its definitions with the keyword
“inline”.
Example
inline int cube(int s)
{
return s*s*s;
}
4.2 Inline Function
4.2 Inline Function
• #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
4.2 Inline Function : Why to use –
• In many places we create the functions for small work/functionality
which contain simple and less number of executable instruction.
• Imagine their calling overhead each time they are being called by
callers.
•
4.2 Inline Function : Why to use –
1. When a normal function call instruction is encountered,
2. the program stores the memory address of the instructions
immediately following the function call statement,
3. loads the function being called into the memory, copies argument
values, jumps to the memory location of the called function,
4. executes the function codes, stores the return value of the function,
5. and then jumps back to the address of the instruction that was
saved just before executing the called function.
6. Too much run time overhead.
4.2 Inline Function : Why to use –
• The C++ inline function provides an alternative.
• With inline keyword, the compiler replaces the function call
statement with the function code itself (process called expansion)
and then compiles the entire code.
• Thus, with inline functions, the compiler does not have to jump to
another location to execute the function, and then jump back as the
code of the called function is already available to the calling program.
4.2 Inline Function : Pros :-
1. It speeds up your program by avoiding function calling overhead.
2. It save overhead of variables push/pop on the stack, when function
calling happens.
3. It save overhead of return call from a function.
4. It increases locality of reference by utilizing instruction cache.
5. You can put a function definition in a header file and it can be
included in multiple compilation unit.
4.2 Inline Function : Cons
1. It increases the executable size due to code expansion.
2. Which means if you change the code of the inlined function, you
would need to recompile all the code using it to make sure it will be
updated
3. As mentioned above it increases the executable size, which may
cause thrashing in memory. More number of page fault bringing
down your program performance.
4. Sometimes not useful for example in embedded system where large
executable size is not preferred at all due to memory constraints.
4.2 Inline Function : When to use -
• Function can be made as inline as per programmer need.
• Some useful recommendation are mentioned below-
• 1. Use inline function when performance is needed.
• 2. Use inline function over macros.
4.2 Inline Function : Restrictions
• 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.
Module 1- Section 4- Lecture 4
4.3 Default Arguments
4.3 Default Arguments
4.3 Default Arguments
• In C++ programming, we can provide default values
for function parameters.
• If a function with default arguments is called without passing
arguments, then the default parameters are used.
• However, if arguments are passed while calling the function, the
default arguments are ignored.
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}
4.3 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.
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}
4.3 Default Arguments
4.3 Default Arguments : program
4.3 Default Arguments : program
• // Program of default argument
• #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 main()
• {
• cout << sum(10, 15) << endl;
• cout << sum(10, 15, 25) << endl;
• cout << sum(10, 15, 25, 30) << endl;
• return 0;
• }
4.3 Default Arguments : Key Points:
• Default arguments are different 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 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.
4.3 Default Arguments
• When Function overloading is done along with default values. Then
we need to make sure it will not be ambiguous.
• The compiler will throw error if ambiguous.
Module 1- Section 4- Lecture 4
4.4 Function Overloading
4.4 Function Overloading
• Function overloading is a feature in C++ where two or more functions
can have the same name but different parameters.
• The definition of the function must differ from each other
• 1. By number of arguments in the argument list.
• 2. By types of arguments in the argument list.
• 3. Or Both in number and types
• You cannot overload function declarations that differ by return type.
4.4 Function Overloading
• Examples
• int myFunction() { }
• int myFunction(int a) { }
• float myFunction(double a) { }
• int myFunction(int a, double b) { }
4.4 Function Overloading
• The advantage of Function overloading is that it increases the
readability of the program because you don't need to use different
names for the same action.
4.4 Function Overloading Example
4.4 Function Overloading Example
• // Function Overloading Example
• #include <iostream>
• using namespace std;
•
• void display(int);
• void display(float);
• void display(int, float);
•
• int main()
• {
•
• int a = 5;
• float b = 5.5;
•
• display(a);
• display(b);
• display(a, b);
•
• return 0;
• }
• void display(int var) {
• cout << "Integer number: " << var << endl;
• }
• void display(float var) {
• cout << "Float number: " << var << endl;
• }
• void display(int var1, float var2) {
• cout << "Integer number: " << var1;
• cout << " and float number:" << var2;
• }
4.4 Function Overloading and Ambiguity
• When the compiler is unable to decide which function is to be
invoked among the overloaded function, this situation is known
as Ambiguity in function overloading.
• When the compiler shows the ambiguity error, the compiler does not
run the program.
4.4 Function Overloading and Ambiguity
• Causes of Ambiguity in Function Overloading:
1. Type Conversion.
2. Function with default arguments.
3. Function with pass by reference.
4.4 Function Overloading and Ambiguity
1. Type Conversion.
Reason
The fun(1.2) calls the second function
according to our prediction.
But, this does not refer to any function as in
C++, all the floating point constants are
treated as double not as a float.
So 1.2 is treated as double not float.
If we replace float to double, the program
works.
4.4 Function Overloading and Ambiguity
// Ambiguity in Function overloading
// 1. By Type conversion
#include<iostream>
using namespace std;
void fun(int);
void fun(float);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(float j)
{
std::cout << "Value of j is : " <<j<< std::endl;
}
int main()
{
fun(12);
fun(1.2);
return 0;
}
4.4 Ambiguity by Default Arguments
Explanation
1. The above example shows an error "call
of overloaded 'fun(int)' is ambiguous".
2. The fun(int a, int b=9) can be called in
two ways:
3. first is by calling the function with one
argument, i.e., fun(12)
4. and another way is calling the function
with two arguments, i.e., fun(4,5).
5. The fun(int i) function is invoked with
one argument i.e. fun(12).
6. Therefore, the compiler could not be
able to select among fun(int i) and
fun(int a,int b=9) and show an error
message that function call is
ambiguous.
4.4 Ambiguity by Default Arguments
• // Ambiguity in Function overloading
• // By Default Arguments
• #include<iostream>
• using namespace std;
•
• void fun(int i)
• {
• cout << "Value of i is : " <<i<< std::endl;
• }
• void fun(int a,int b=9)
• {
• cout << "Value of a is : " <<a<< std::endl;
• cout << "Value of b is : " <<b<< std::endl;
• }
• int main()
• {
• fun(12);
• return 0;
• }
4.4 Ambiguity by Call By Reference
Explanation
1. The above example shows an
error "call of overloaded
'fun(int&)' is ambiguous".
2. The first function takes one
integer argument and the second
function takes a reference
parameter as an argument.
3. In this case, the compiler does
not know which function is
needed by the user as there is no
syntactical difference between
the fun(int) and fun(int &).
4.4 Ambiguity by Call By Reference
// Ambiguity in Function overloading
// Ambiguity because of call by reference
include <iostream>
using namespace std;
void fun(int);
void fun(int &);
int main()
{
int a=10;
fun(a); // error, which fun()?
return 0;
}
void fun(int x)
{
std::cout << "Value of x is : "
<<x<< std::endl;
}
void fun(int &b)
{
cout << "Value of b is : " <<b<<
std::endl;
}
[Error] call of overloaded 'fun(int&)' is
ambiguous
References
• https://www.tutorialspoint.com/cplusplus/cpp_functions.htm
• https://www.geeksforgeeks.org/inline-functions-cpp/
• https://www.edureka.co/blog/function-overloading-in-cpp/#what
• https://www.edureka.co/blog/function-overloading-in-
cpp/#ambiguity

More Related Content

Similar to OOP-Module-1-Section-4-LectureNo1-5.pptx

662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdfManiMala75
 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2sumitbardhan
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++Vraj Patel
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptAmanuelZewdie4
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptxzueZ3
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptxmiki304759
 
Functions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothiFunctions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothiSowmya Jyothi
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - FunctionsMichael Heron
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxKhurramKhan173
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Function Overloading,Inline Function and Recursion in C++ By Faisal ShahzadFunction Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Function Overloading,Inline Function and Recursion in C++ By Faisal ShahzadFaisal Shehzad
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)Faizan Janjua
 
Inline function
Inline functionInline function
Inline functionTech_MX
 

Similar to OOP-Module-1-Section-4-LectureNo1-5.pptx (20)

arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
Functions
FunctionsFunctions
Functions
 
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf
 
358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2358 33 powerpoint-slides_2-functions_chapter-2
358 33 powerpoint-slides_2-functions_chapter-2
 
Function
Function Function
Function
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Functions
FunctionsFunctions
Functions
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
Functions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothiFunctions in c mrs.sowmya jyothi
Functions in c mrs.sowmya jyothi
 
CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Function Overloading,Inline Function and Recursion in C++ By Faisal ShahzadFunction Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
 
4th unit full
4th unit full4th unit full
4th unit full
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
 
Inline function
Inline functionInline function
Inline function
 

More from sarthakgithub

Access Modifiers in Java.pptx
 Access Modifiers in Java.pptx Access Modifiers in Java.pptx
Access Modifiers in Java.pptxsarthakgithub
 
Data Path Design and Bus Organization.pptx
Data Path Design and Bus Organization.pptxData Path Design and Bus Organization.pptx
Data Path Design and Bus Organization.pptxsarthakgithub
 
Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptxsarthakgithub
 
Flow Control (1).ppt
Flow Control (1).pptFlow Control (1).ppt
Flow Control (1).pptsarthakgithub
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.pptsarthakgithub
 
BCA Abstraction.pptx
BCA Abstraction.pptxBCA Abstraction.pptx
BCA Abstraction.pptxsarthakgithub
 
BCA Final Keyword.pptx
BCA Final Keyword.pptxBCA Final Keyword.pptx
BCA Final Keyword.pptxsarthakgithub
 
BCA Super Keyword.pptx
BCA Super Keyword.pptxBCA Super Keyword.pptx
BCA Super Keyword.pptxsarthakgithub
 

More from sarthakgithub (10)

Access Modifiers in Java.pptx
 Access Modifiers in Java.pptx Access Modifiers in Java.pptx
Access Modifiers in Java.pptx
 
ppt-2.pptx
ppt-2.pptxppt-2.pptx
ppt-2.pptx
 
soumay.pptx
soumay.pptxsoumay.pptx
soumay.pptx
 
Data Path Design and Bus Organization.pptx
Data Path Design and Bus Organization.pptxData Path Design and Bus Organization.pptx
Data Path Design and Bus Organization.pptx
 
Python Unit II.pptx
Python Unit II.pptxPython Unit II.pptx
Python Unit II.pptx
 
Flow Control (1).ppt
Flow Control (1).pptFlow Control (1).ppt
Flow Control (1).ppt
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.ppt
 
BCA Abstraction.pptx
BCA Abstraction.pptxBCA Abstraction.pptx
BCA Abstraction.pptx
 
BCA Final Keyword.pptx
BCA Final Keyword.pptxBCA Final Keyword.pptx
BCA Final Keyword.pptx
 
BCA Super Keyword.pptx
BCA Super Keyword.pptxBCA Super Keyword.pptx
BCA Super Keyword.pptx
 

Recently uploaded

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 

Recently uploaded (20)

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 

OOP-Module-1-Section-4-LectureNo1-5.pptx

  • 1. Functions In C++ Presented by: Mr. Sachin Sharma, Dr. Vinod Jain , Ms. Kriti Bansal Assistant Professor, Dept. Of CE&A GLA University, Mathura
  • 2. Syllabus 4.0 Functions In C++ 4.1 Call by Value & Reference 4.2 Inline Function 4.3 Default Arguments 4.4 Function Overloading. <Subject Code> <Name of Subject> 2
  • 3. Module 1- Section 4- Lecture 1 4.0 Functions In C++
  • 5. 4.0 Functions In C++ • A function is a group of statements that together perform a task. • Every C++ program has at least one function, which is main()
  • 6. 4.0 Functions In C++ A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. Defining a Function The general form of a C++ function definition is as follows − return_type function_name( parameter list ) { body of the function }
  • 7. 4.0 Functions In C++ : Defining a Function
  • 8. 4.0 Functions In C++ • 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. int fact(int no) { int i,f=1; for(i=1;i<=no;i++) f=f*i; return(f); }
  • 9. 4.0 Functions In C++ • Function Name − • This is the actual name of the function. • The function name and the parameter list together constitute the function signature. • Example • Here function name is fact int fact(int no) { int i,f=1; for(i=1;i<=no;i++) f=f*i; return(f); }
  • 10. 4.0 Functions In C++ • Parameters − • When a function is invoked, you pass a value to the parameter. • 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. • Example (int no) int fact(int no) { int i,f=1; for(i=1;i<=no;i++) f=f*i; return(f); }
  • 11. 4.0 Functions In C++ • Function Body − • The function body contains a collection of statements that define what the function does. • Example Function body here is { int i,f=1; for(i=1;i<=no;i++) f=f*i; return(f); } int fact(int no) { int i,f=1; for(i=1;i<=no;i++) f=f*i; return(f); }
  • 12. 4.0 Functions In C++ • // A program to write and use a function to calculate factorial of a number
  • 13.
  • 14. 4.0 Functions In C++ // A program to write and use a function to // calculate factorial of a number #include<iostream> #include<conio.h> using namespace std; //function prototype int fact(int); //main function int main() { int n,factorial; cout<<"Enter the n : "<<endl; cin>>n; //calculate factorial using function. factorial=fact(n); //print factorial cout<<"Factorial of "<<n<<" is "<<factorial; return 0; } //function int fact(int no) { int i,f=1; for(i=1;i<=no;i++) f=f*i; return(f); } Output Enter the no. 5 Factorial of 5 is 120
  • 15. 4.0 Functions In C++ • Parameter Passing to functions 1. Actual Parameters 2. Formal parameters
  • 16. 4.0 Functions In C++ • Parameter Passing to functions Actual Parameters • The parameters passed to function are called actual parameters. • For example, in the above program 5 is actual parameters. • Formal parameters • The parameters received by function are called formal parameters. • For example, in the above program no is a formal parameter.
  • 17. Module 1- Section 4- Lecture 2 4.1 Call by Value & Reference
  • 18. 4.1 Call by Value & Reference • There are two most popular ways to pass parameters. 1. Call by Value 2. Call by reference
  • 19. 4.1 Call by Value & Reference • There are two most popular ways to pass parameters. 1. Call by Value 2. Call by reference
  • 20. 4.1 Call by Value & Reference
  • 21. 4.1 Call by Value • Call by Value: • In this parameter passing method, values of actual parameters are copied to function’s formal parameters. • The two types of parameters are stored in different memory locations. • So any changes made inside functions are not reflected in actual parameters of caller.
  • 22.
  • 23. 4.1 Call by Value • // Call by value • #include <iostream> • using namespace std; • • // function declaration • void swap(int x, int y); • • int main () { • // local variable declaration: • int a = 100; • int b = 200; • • cout << "Before swap, value of a :" << a << endl; • cout << "Before swap, value of b :" << b << endl; • • // calling a function to swap the values. • swap(a, b); • • cout << "After swap, value of a :" << a << endl; • cout << "After swap, value of b :" << b << endl; • return 0; • } • // function definition to swap the values. • void swap(int x, int y) { • int temp; • temp = x; • x = y; • y = temp; • • return; • } • Output • Before swap, value of a :100 • Before swap, value of b :200 • After swap, value of a :100 • After swap, value of b :200
  • 24. 4.1 Call by Reference • call by reference • The call by reference method of passing arguments to a function 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 passed argument.
  • 25. 4.1 Call by Reference • call by reference • To pass the value by reference, argument reference is passed to the functions just like any other value. • So accordingly you need to declare the function parameters as reference types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments. void swap(int &x, int &y) { }
  • 26. 4.1 Call by Reference • Program to swap two numbers using call by reference • Make a swap() function which pass parameters by reference void swap(int &x, int &y) { int temp; temp = x; x = y; y = temp; return; }
  • 27.
  • 28. 4.1 Differnce between Call by Value & Reference
  • 29. Module 1- Section 4- Lecture 3 4.2 Inline Function
  • 30. 4.2 Inline Function • The inline functions are a C++ enhancement feature to decrease the execution time of a program. • 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. • Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called.
  • 32. 4.2 Inline Function : How to make function inline: To make any function as inline, start its definitions with the keyword “inline”. Example inline int cube(int s) { return s*s*s; }
  • 34. 4.2 Inline Function • #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
  • 35. 4.2 Inline Function : Why to use – • In many places we create the functions for small work/functionality which contain simple and less number of executable instruction. • Imagine their calling overhead each time they are being called by callers. •
  • 36. 4.2 Inline Function : Why to use – 1. When a normal function call instruction is encountered, 2. the program stores the memory address of the instructions immediately following the function call statement, 3. loads the function being called into the memory, copies argument values, jumps to the memory location of the called function, 4. executes the function codes, stores the return value of the function, 5. and then jumps back to the address of the instruction that was saved just before executing the called function. 6. Too much run time overhead.
  • 37. 4.2 Inline Function : Why to use – • The C++ inline function provides an alternative. • With inline keyword, the compiler replaces the function call statement with the function code itself (process called expansion) and then compiles the entire code. • Thus, with inline functions, the compiler does not have to jump to another location to execute the function, and then jump back as the code of the called function is already available to the calling program.
  • 38. 4.2 Inline Function : Pros :- 1. It speeds up your program by avoiding function calling overhead. 2. It save overhead of variables push/pop on the stack, when function calling happens. 3. It save overhead of return call from a function. 4. It increases locality of reference by utilizing instruction cache. 5. You can put a function definition in a header file and it can be included in multiple compilation unit.
  • 39. 4.2 Inline Function : Cons 1. It increases the executable size due to code expansion. 2. Which means if you change the code of the inlined function, you would need to recompile all the code using it to make sure it will be updated 3. As mentioned above it increases the executable size, which may cause thrashing in memory. More number of page fault bringing down your program performance. 4. Sometimes not useful for example in embedded system where large executable size is not preferred at all due to memory constraints.
  • 40. 4.2 Inline Function : When to use - • Function can be made as inline as per programmer need. • Some useful recommendation are mentioned below- • 1. Use inline function when performance is needed. • 2. Use inline function over macros.
  • 41. 4.2 Inline Function : Restrictions • 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.
  • 42. Module 1- Section 4- Lecture 4 4.3 Default Arguments
  • 44. 4.3 Default Arguments • In C++ programming, we can provide default values for function parameters. • If a function with default arguments is called without passing arguments, then the default parameters are used. • However, if arguments are passed while calling the function, the default arguments are ignored. int sum(int x, int y, int z=0, int w=0) { return (x + y + z + w); }
  • 45. 4.3 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. int sum(int x, int y, int z=0, int w=0) { return (x + y + z + w); }
  • 48.
  • 49. 4.3 Default Arguments : program • // Program of default argument • #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 main() • { • cout << sum(10, 15) << endl; • cout << sum(10, 15, 25) << endl; • cout << sum(10, 15, 25, 30) << endl; • return 0; • }
  • 50. 4.3 Default Arguments : Key Points: • Default arguments are different 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 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.
  • 51. 4.3 Default Arguments • When Function overloading is done along with default values. Then we need to make sure it will not be ambiguous. • The compiler will throw error if ambiguous.
  • 52. Module 1- Section 4- Lecture 4 4.4 Function Overloading
  • 53.
  • 54. 4.4 Function Overloading • Function overloading is a feature in C++ where two or more functions can have the same name but different parameters. • The definition of the function must differ from each other • 1. By number of arguments in the argument list. • 2. By types of arguments in the argument list. • 3. Or Both in number and types • You cannot overload function declarations that differ by return type.
  • 55. 4.4 Function Overloading • Examples • int myFunction() { } • int myFunction(int a) { } • float myFunction(double a) { } • int myFunction(int a, double b) { }
  • 56. 4.4 Function Overloading • The advantage of Function overloading is that it increases the readability of the program because you don't need to use different names for the same action.
  • 58.
  • 59. 4.4 Function Overloading Example • // Function Overloading Example • #include <iostream> • using namespace std; • • void display(int); • void display(float); • void display(int, float); • • int main() • { • • int a = 5; • float b = 5.5; • • display(a); • display(b); • display(a, b); • • return 0; • } • void display(int var) { • cout << "Integer number: " << var << endl; • } • void display(float var) { • cout << "Float number: " << var << endl; • } • void display(int var1, float var2) { • cout << "Integer number: " << var1; • cout << " and float number:" << var2; • }
  • 60. 4.4 Function Overloading and Ambiguity • When the compiler is unable to decide which function is to be invoked among the overloaded function, this situation is known as Ambiguity in function overloading. • When the compiler shows the ambiguity error, the compiler does not run the program.
  • 61. 4.4 Function Overloading and Ambiguity • Causes of Ambiguity in Function Overloading: 1. Type Conversion. 2. Function with default arguments. 3. Function with pass by reference.
  • 62. 4.4 Function Overloading and Ambiguity 1. Type Conversion.
  • 63. Reason The fun(1.2) calls the second function according to our prediction. But, this does not refer to any function as in C++, all the floating point constants are treated as double not as a float. So 1.2 is treated as double not float. If we replace float to double, the program works.
  • 64. 4.4 Function Overloading and Ambiguity // Ambiguity in Function overloading // 1. By Type conversion #include<iostream> using namespace std; void fun(int); void fun(float); void fun(int i) { std::cout << "Value of i is : " <<i<< std::endl; } void fun(float j) { std::cout << "Value of j is : " <<j<< std::endl; } int main() { fun(12); fun(1.2); return 0; }
  • 65. 4.4 Ambiguity by Default Arguments
  • 66.
  • 67. Explanation 1. The above example shows an error "call of overloaded 'fun(int)' is ambiguous". 2. The fun(int a, int b=9) can be called in two ways: 3. first is by calling the function with one argument, i.e., fun(12) 4. and another way is calling the function with two arguments, i.e., fun(4,5). 5. The fun(int i) function is invoked with one argument i.e. fun(12). 6. Therefore, the compiler could not be able to select among fun(int i) and fun(int a,int b=9) and show an error message that function call is ambiguous.
  • 68. 4.4 Ambiguity by Default Arguments • // Ambiguity in Function overloading • // By Default Arguments • #include<iostream> • using namespace std; • • void fun(int i) • { • cout << "Value of i is : " <<i<< std::endl; • } • void fun(int a,int b=9) • { • cout << "Value of a is : " <<a<< std::endl; • cout << "Value of b is : " <<b<< std::endl; • } • int main() • { • fun(12); • return 0; • }
  • 69. 4.4 Ambiguity by Call By Reference
  • 70.
  • 71. Explanation 1. The above example shows an error "call of overloaded 'fun(int&)' is ambiguous". 2. The first function takes one integer argument and the second function takes a reference parameter as an argument. 3. In this case, the compiler does not know which function is needed by the user as there is no syntactical difference between the fun(int) and fun(int &).
  • 72. 4.4 Ambiguity by Call By Reference // Ambiguity in Function overloading // Ambiguity because of call by reference include <iostream> using namespace std; void fun(int); void fun(int &); int main() { int a=10; fun(a); // error, which fun()? return 0; } void fun(int x) { std::cout << "Value of x is : " <<x<< std::endl; } void fun(int &b) { cout << "Value of b is : " <<b<< std::endl; } [Error] call of overloaded 'fun(int&)' is ambiguous
  • 73. References • https://www.tutorialspoint.com/cplusplus/cpp_functions.htm • https://www.geeksforgeeks.org/inline-functions-cpp/ • https://www.edureka.co/blog/function-overloading-in-cpp/#what • https://www.edureka.co/blog/function-overloading-in- cpp/#ambiguity