SlideShare a Scribd company logo
1 of 8
ASSIGNMENT NO:
SUBJECT NAME:
TOPIC:
Function Overloading in C++ and Its Example
Inline Function in C++ and Its Example
Recursion in C++ and Its Example
SUBMITTED TO:
SIR RAO TOUSEEF
SUBMITTED BY:
Faisal Shehzad
ROLL: NO:
SP17-MCS-020
SECTION:
MCS-B12-A
COMSATS Institute of Information
Technology Vehari Campus
15-May-2017Date:
Function Overloading in C++
Function overloading is a feature in C++ where two or more functions can have
the same name but different parameters.
Function overloading can be considered as an example of polymorphism feature
in C++.
Advantages :-
 Overloaded methods give programmers the flexibility to call a similar
method for different types of data.
 Function overloading is done for code reusability, to save efforts, and
also to save memory.
Disadvantages :-
 There aren’t many notable disadvantages of using function overloading
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* c) {
cout << " Here is char* " << c << endl;
}
int main() {
print(10);
print(10.10);
print("ten");
return 0;
}
The output of following code is
shown in the figure.
Following is a simple C++ example to demonstrate function overloading.
#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;
}
The output of following code is shown in the
figure.
Inline Functions in C++
Inline function is one of the important feature of C++. So, let’s first understand
why inline functions are used and what is the purpose of inline function?
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.
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.
Following is a simple C++ example to demonstrate Inline function.
#include <iostream>
using namespace std;
class operation
{
int a,b,add,sub,mul;
float div;
public:
void get();
void sum();
void difference();
void product();
void division();
};
inline void operation :: get()
{
cout << "Enter first value:";
cin >> a;
cout << "Enter second value:";
cin >> b;
}
inline void operation :: sum()
{
add = a+b;
cout << "Addition of two numbers: " << a+b << "n";
}
inline void operation :: difference()
{
sub = a-b;
cout << "Difference of two numbers: " << a-b << "n";
}
inline void operation :: product()
{
mul = a*b;
cout << "Product of two numbers: " << a*b << "n";
}
inline void operation ::division()
{
div=a/b;
cout<<"Division of two numbers: "<<a/b<<"n" ;
}
int main()
{
cout << "Program using inline functionn";
operation s;
s.get();
s.sum();
s.difference();
s.product();
s.division();
return 0;
}
The output of following code is shown in
the figure.
Recursion
What is Recursion?
The process in which a function calls itself directly or indirectly is called recursion and
the corresponding function is called as recursive function. Using recursive algorithm,
certain problems can be solved quite easily.
What Is Base ConditionIn Recursion?
In recursive program, the solution to base case is provided and solution of bigger
problem is expressed in terms of smaller problems.
intfact(intn)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
In the above example, base case for n < = 1 is defined and larger value of
number can be solved by converting to smaller one till base case is reached.
Why Stack Overflow Error Occurs In Recursion?
If base case is not reached or not defined, then stack overflow problem may
arise. Let us take an example to understand this.
int fact(int n)
{
// wrong base case (it may cause
// stack overflow).
if (n == 100)
return 1;
else
return n*fact(n-1);
}
Let us take the example how recursion works by taking a simple
function.
/* Example Program For Factorial Value Using Recursion In C++ */
#include<iostream>
#include<conio.h>
using namespace std;
//Function
long factorial(int);
int main()
{
// Variable Declaration
int counter, n;
// Get Input Value
cout<<"Enter the Number :";
cin>>n;
// Factorial Function Call
cout<<n<<" Factorial Value Is "<<factorial(n);
// Wait For Output Screen
getch();
return 0;
}
// Factorial recursion Function
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
The output of following code is shown in the
figure.

More Related Content

What's hot (20)

Modular Programming in C
Modular Programming in CModular Programming in C
Modular Programming in C
 
User defined functions.1
User defined functions.1User defined functions.1
User defined functions.1
 
Code optimization
Code optimizationCode optimization
Code optimization
 
Optimization
OptimizationOptimization
Optimization
 
Loop optimization
Loop optimizationLoop optimization
Loop optimization
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
3 Function Overloading
3 Function Overloading3 Function Overloading
3 Function Overloading
 
Code optimization
Code optimizationCode optimization
Code optimization
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Compiler optimization techniques
Compiler optimization techniquesCompiler optimization techniques
Compiler optimization techniques
 
Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
 
Code optimisation presnted
Code optimisation presntedCode optimisation presnted
Code optimisation presnted
 
Compiler optimization
Compiler optimizationCompiler optimization
Compiler optimization
 
Compiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent OptimizationsCompiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent Optimizations
 
Function overloading in c++
Function overloading in c++Function overloading in c++
Function overloading in c++
 
Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
 
Optimization in Programming languages
Optimization in Programming languagesOptimization in Programming languages
Optimization in Programming languages
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Functions in C - Programming
Functions in C - Programming Functions in C - Programming
Functions in C - Programming
 
Issues in design_of_code_generator
Issues in design_of_code_generatorIssues in design_of_code_generator
Issues in design_of_code_generator
 

Similar to Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad

Inline function
Inline functionInline function
Inline functionTech_MX
 
inline function
inline function inline function
inline function imran khan
 
Compiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCompiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCAFxX
 
C++ 2
C++ 2C++ 2
C++ 2jani
 
MarGotAspect - An AspectC++ code generator for the mARGOt framework
MarGotAspect - An AspectC++ code generator for the mARGOt frameworkMarGotAspect - An AspectC++ code generator for the mARGOt framework
MarGotAspect - An AspectC++ code generator for the mARGOt frameworkLeonardo Arcari
 
wepik-mastering-function-in-c-a-comprehensive-guide-20231220121719HZHU.pptx
wepik-mastering-function-in-c-a-comprehensive-guide-20231220121719HZHU.pptxwepik-mastering-function-in-c-a-comprehensive-guide-20231220121719HZHU.pptx
wepik-mastering-function-in-c-a-comprehensive-guide-20231220121719HZHU.pptxavishekpradhan24
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptxmiki304759
 
OOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxOOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxsarthakgithub
 
C optimization notes
C optimization notesC optimization notes
C optimization notesFyaz Ghaffar
 
Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...Sar
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignmentAhmad Kamal
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1ReKruiTIn.com
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c languageTanmay Modi
 

Similar to Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad (20)

Inline function
Inline functionInline function
Inline function
 
inline function
inline function inline function
inline function
 
inline function
inline functioninline function
inline function
 
Compiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCompiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flattening
 
C++ 2
C++ 2C++ 2
C++ 2
 
C++
C++C++
C++
 
MarGotAspect - An AspectC++ code generator for the mARGOt framework
MarGotAspect - An AspectC++ code generator for the mARGOt frameworkMarGotAspect - An AspectC++ code generator for the mARGOt framework
MarGotAspect - An AspectC++ code generator for the mARGOt framework
 
wepik-mastering-function-in-c-a-comprehensive-guide-20231220121719HZHU.pptx
wepik-mastering-function-in-c-a-comprehensive-guide-20231220121719HZHU.pptxwepik-mastering-function-in-c-a-comprehensive-guide-20231220121719HZHU.pptx
wepik-mastering-function-in-c-a-comprehensive-guide-20231220121719HZHU.pptx
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
Presentation 2.pptx
Presentation 2.pptxPresentation 2.pptx
Presentation 2.pptx
 
OOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxOOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptx
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
C optimization notes
C optimization notesC optimization notes
C optimization notes
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignment
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c language
 

Recently uploaded

Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 

Recently uploaded (20)

Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 

Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad

  • 1. ASSIGNMENT NO: SUBJECT NAME: TOPIC: Function Overloading in C++ and Its Example Inline Function in C++ and Its Example Recursion in C++ and Its Example SUBMITTED TO: SIR RAO TOUSEEF SUBMITTED BY: Faisal Shehzad ROLL: NO: SP17-MCS-020 SECTION: MCS-B12-A COMSATS Institute of Information Technology Vehari Campus 15-May-2017Date:
  • 2. Function Overloading in C++ Function overloading is a feature in C++ where two or more functions can have the same name but different parameters. Function overloading can be considered as an example of polymorphism feature in C++. Advantages :-  Overloaded methods give programmers the flexibility to call a similar method for different types of data.  Function overloading is done for code reusability, to save efforts, and also to save memory. Disadvantages :-  There aren’t many notable disadvantages of using function overloading 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* c) { cout << " Here is char* " << c << endl; } int main() { print(10); print(10.10); print("ten"); return 0; } The output of following code is shown in the figure.
  • 3. Following is a simple C++ example to demonstrate function overloading. #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; } The output of following code is shown in the figure. Inline Functions in C++ Inline function is one of the important feature of C++. So, let’s first understand why inline functions are used and what is the purpose of inline function? 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
  • 4. 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. 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
  • 5. 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. Following is a simple C++ example to demonstrate Inline function. #include <iostream> using namespace std; class operation { int a,b,add,sub,mul; float div; public: void get(); void sum(); void difference(); void product(); void division(); }; inline void operation :: get() { cout << "Enter first value:"; cin >> a; cout << "Enter second value:"; cin >> b; } inline void operation :: sum()
  • 6. { add = a+b; cout << "Addition of two numbers: " << a+b << "n"; } inline void operation :: difference() { sub = a-b; cout << "Difference of two numbers: " << a-b << "n"; } inline void operation :: product() { mul = a*b; cout << "Product of two numbers: " << a*b << "n"; } inline void operation ::division() { div=a/b; cout<<"Division of two numbers: "<<a/b<<"n" ; } int main() { cout << "Program using inline functionn"; operation s; s.get(); s.sum(); s.difference(); s.product(); s.division(); return 0; } The output of following code is shown in the figure. Recursion What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily.
  • 7. What Is Base ConditionIn Recursion? In recursive program, the solution to base case is provided and solution of bigger problem is expressed in terms of smaller problems. intfact(intn) { if (n < = 1) // base case return 1; else return n*fact(n-1); } In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting to smaller one till base case is reached. Why Stack Overflow Error Occurs In Recursion? If base case is not reached or not defined, then stack overflow problem may arise. Let us take an example to understand this. int fact(int n) { // wrong base case (it may cause // stack overflow). if (n == 100) return 1; else return n*fact(n-1); } Let us take the example how recursion works by taking a simple function. /* Example Program For Factorial Value Using Recursion In C++ */ #include<iostream> #include<conio.h> using namespace std; //Function long factorial(int); int main() { // Variable Declaration int counter, n; // Get Input Value cout<<"Enter the Number :"; cin>>n; // Factorial Function Call
  • 8. cout<<n<<" Factorial Value Is "<<factorial(n); // Wait For Output Screen getch(); return 0; } // Factorial recursion Function long factorial(int n) { if (n == 0) return 1; else return(n * factorial(n-1)); } The output of following code is shown in the figure.