SlideShare a Scribd company logo
5
5 Function structure in c++
Let's break down the components of a C++ function:
return_type: This is the data type of the value that the function will return after it has
executed its task. If the function doesn't return a value, you can use void as the return
type.
function_name: This is the name you choose for your function, following the naming rules
of C++.
parameters: These are optional input values that the function can accept. Parameters
are enclosed in parentheses and separated by commas. They allow you to pass
information into the function for processing.
Function body: This is the actual code that performs the specific task of the function.
return (optional): If the return_type is not void, you can use the return statement to send a
Most read
6
6 Function Return Type in C++
The return type is the type of value returned by the function. A function in C++ may or may
not return a value. If the function does not return a value then its return type is void. Value
is returned from a function using the return statement. Control is transferred back to the
caller when the return statement is executed. If the function returns a value then we need
to specify its data type, like int, char, or float.
Note: Only one value can be returned from a function in C++. It is mandatory to return a
value for functions with a non-void return type.
For example, consider a function calculateFactorial which calculates the factorial of a
number and returns an integer value. We can see its return type is int.
int calculateFactorial( int num)
{
int fact=1;
for(int i=1;i<=num;i++)
fact*=i;
return fact; }
Most read
7
7 Types of Functions
1. User Defined Function are user/customer-defined blocks of code specially
customized to reduce the complexity of big programs. They are also commonly
known as “tailor-made functions” which are built only to satisfy the condition in
which the user is facing issues meanwhile reducing the complexity of the whole
program.
2. Library functions are also called “built-in Functions“. These functions are part of a
compiler package that is already defined and consists of a special function with
special and different meanings. Built-in Function gives us an edge as we can directly
use them without defining them whereas in the user-defined function we have to
declare and define a function before using them.
For Example: sqrt(), sort(),pow(),reverse(),abs(), etc.
Most read
1
Functions in C++
Ahmad Baryal
Saba Institute of Higher Education
Computer Science Faculty
Oct 21, 2024
2 Table of contents
 What is function?
 Why do we need functions?
 Function structure
 Function declaration
 Types of functions
 Function calling
 Function call methods
 Recursion
 Inline Functions
 Function overloading
3 Function C++
 A function is a set of statements that takes input, does some specific
computation, and produces output. The idea is to put some commonly or
repeatedly done tasks together to make a function so that instead of writing the
same code again and again for different inputs, we can call this function.
 They also enable code reusability by allowing you to call a function multiple times
within your program.
4 Why Do we Need Functions?
• Functions help us in reducing code redundancy. If functionality is performed
at multiple places in software, then rather than writing the same code,
again and again, we create a function and call it everywhere. This also
helps in maintenance as we have to make changes in only one place if
we make changes to the functionality in future.
• Functions make code modular. Consider a big file having many lines of
code. It becomes really simple to read and use the code, if the code is
divided into functions.
• Functions provide abstraction. For example, we can use library functions
without worrying about their internal work.
5 Function structure in c++
Let's break down the components of a C++ function:
return_type: This is the data type of the value that the function will return after it has
executed its task. If the function doesn't return a value, you can use void as the return
type.
function_name: This is the name you choose for your function, following the naming rules
of C++.
parameters: These are optional input values that the function can accept. Parameters
are enclosed in parentheses and separated by commas. They allow you to pass
information into the function for processing.
Function body: This is the actual code that performs the specific task of the function.
return (optional): If the return_type is not void, you can use the return statement to send a
6 Function Return Type in C++
The return type is the type of value returned by the function. A function in C++ may or may
not return a value. If the function does not return a value then its return type is void. Value
is returned from a function using the return statement. Control is transferred back to the
caller when the return statement is executed. If the function returns a value then we need
to specify its data type, like int, char, or float.
Note: Only one value can be returned from a function in C++. It is mandatory to return a
value for functions with a non-void return type.
For example, consider a function calculateFactorial which calculates the factorial of a
number and returns an integer value. We can see its return type is int.
int calculateFactorial( int num)
{
int fact=1;
for(int i=1;i<=num;i++)
fact*=i;
return fact; }
7 Types of Functions
1. User Defined Function are user/customer-defined blocks of code specially
customized to reduce the complexity of big programs. They are also commonly
known as “tailor-made functions” which are built only to satisfy the condition in
which the user is facing issues meanwhile reducing the complexity of the whole
program.
2. Library functions are also called “built-in Functions“. These functions are part of a
compiler package that is already defined and consists of a special function with
special and different meanings. Built-in Function gives us an edge as we can directly
use them without defining them whereas in the user-defined function we have to
declare and define a function before using them.
For Example: sqrt(), sort(),pow(),reverse(),abs(), etc.
8 Calling a Function
In C++, you can call a function by specifying the function's name, followed by
parentheses containing any necessary arguments (if the function takes parameters).
Here's the basic syntax for calling a function in C++:
// Function declaration
int add(int a, int b);
int main() {
int result = add(5, 3); // Calling the add function
cout << "Result: " << result << endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
9 There are two most popular ways to pass parameters:
1. Pass by Value: In this parameter passing method, values of actual parameters are
copied to the function’s formal parameters. The actual and formal parameters are
stored in different memory locations so any changes made in the functions are not
reflected in the actual parameters of the caller.
void incrementByValue(int x) {
x++; // Increment the value of x
cout << "Inside incrementByValue: x = " << x << endl;
}
int main() {
int num = 5;
cout << "Original value of num: " << num << endl;
incrementByValue(num);
cout << "After incrementByValue: num = " << num << endl;
return 0;
}
10 There are two most popular ways to pass parameters:
1. Pass by Reference: Both actual and formal parameters refer to the same locations, so
any changes made inside the function are reflected in the actual parameters of the
caller.
void incrementByReference(int &x) {
x++; // Increment the value referred to by x
cout << "Inside incrementByReference: x = " << x << endl;
}
int main() {
int num = 5;
cout << "Original value of num: " << num << endl;
incrementByReference(num);
cout << "After incrementByReference: num = " << num << endl;
return 0;
}
11
Difference between call by value and call by reference in C++
Call by value
 A copy of the value is passed to
the function
 Changes made inside the
function are not reflected on
other functions
 Actual and formal arguments will
be created at different memory
location
Call by reference
 An address of value is passed to
the function
 Changes made inside the
function are reflected outside the
function as well
 Actual and formal arguments will
be created at same memory
location.
12 Recursion in function
Recursion is a programming concept where a function calls itself directly or indirectly to
solve a problem.
#include <iostream>
using namespace std;
// Recursive factorial function
int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0 || n == 1) {
return 1;
} else {
// Recursive case: n! = n * (n-1)!
return n * factorial(n - 1);
}
}
int main() {
// Example usage of the factorial function
int num = 5;
cout << "Factorial of " << num << " is: " << factorial(num) << endl;
return 0;
}
13 Inline functions
Inline functions in C++ are expanded by the compiler directly at the point of the
function call, eliminating the overhead of a regular function call.
Marked with the inline keyword.
Pros:
• Performance improvement by reducing function call overhead.
• Compiler optimization opportunities.
• Reduced time and space overhead on the call stack.
Cons:
• Potential code bloat due to duplicated code at call sites.
• Compiler might choose not to inline based on its optimization criteria.
• Can reduce code maintainability for complex functions.
14 Inline functions Example
#include <iostream>
using namespace std;
// Definition of an inline function
inline int square(int x) {
return x * x;
}
int main() {
int num = 5;
// Inline function call
int result = square(num);
cout << "Square of " << num << " is: " << result << endl;
return 0; }
15 Function overloading
• Function overloading is a feature in C++ that allows multiple functions in the same scope with
the same name but different parameter lists.
• It provides a way to create functions that perform similar tasks but with variations in the type or
number of parameters.
Overloading Based on the Number and Type of Parameters:
• Overloaded functions must differ in either the number or type of their parameters.
• The compiler determines which function to call based on the number and types of arguments
passed during the function call.
16 Example 1: Overloading Based on Number of Parameters:
#include <iostream>
using namespace std;
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Overloaded function to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
int main() {
cout << "Sum of 2 and 3: " << add(2, 3) << endl;
cout << "Sum of 2, 3, and 4: " << add(2, 3, 4) << endl;
return 0;
}
17 Example 2: Overloading Based on Type of Parameters:
#include <iostream>
using namespace std;
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Overloaded function to concatenate two strings
string add(const string& str1, const string& str2) {
return str1 + str2;
}
int main() {
cout << "Sum of 2 and 3: " << add(2, 3) << endl;
cout << "Concatenation of 'Hello' and ' World': " << add("Hello", " World") <<
endl;
return 0;
}
18 Functions Using Pointers
The function fun() expects a pointer ptr to an integer (or an address of an
integer). It modifies the value at the address ptr. The dereference operator * is
used to access the value at an address. In the statement ‘*ptr = 30’, the value
at address ptr is changed to 30. The address operator & is used to get the
address of a variable of any data type. In the function call statement ‘fun(&x)’,
the address of x is passed so that x can be modified using its address.
// C++ Program to demonstrate working of
// function using pointers
#include <iostream>
using namespace std;
void fun(int* ptr) { *ptr = 30; }
int main()
{
int x = 20;
fun(&x);
cout << "x = " << x;
return 0;
19
Any Questions?

More Related Content

Similar to 6. Functions in C ++ programming object oriented programming (20)

CSC2161Programming_in_Cpp_Lecture notes.pptx
CSC2161Programming_in_Cpp_Lecture notes.pptxCSC2161Programming_in_Cpp_Lecture notes.pptx
CSC2161Programming_in_Cpp_Lecture notes.pptx
winebaldbanituze
 
Chapter 1 (2) array and structure r.pptx
Chapter 1 (2) array and structure r.pptxChapter 1 (2) array and structure r.pptx
Chapter 1 (2) array and structure r.pptx
abenezertekalign118
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
LadallaRajKumar
 
Functions1
Functions1Functions1
Functions1
DrUjwala1
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
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
sarthakgithub
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
C++ Functions.pptx
C++ Functions.pptxC++ Functions.pptx
C++ Functions.pptx
DikshaDani5
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
rebin5725
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
Faizan Janjua
 
Pro
ProPro
Pro
TeshaleSiyum
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
kanaka vardhini
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
bhargavi804095
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
LidetAdmassu
 
Programming Fundamentals lecture-10.pptx
Programming Fundamentals lecture-10.pptxProgramming Fundamentals lecture-10.pptx
Programming Fundamentals lecture-10.pptx
singyali199
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
Cpp functions
Cpp functionsCpp functions
Cpp functions
NabeelaNousheen
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
temkin abdlkader
 
Chapter 6 - Modular Programming- in C++.pptx
Chapter 6 - Modular Programming- in C++.pptxChapter 6 - Modular Programming- in C++.pptx
Chapter 6 - Modular Programming- in C++.pptx
ChereLemma2
 
CSC2161Programming_in_Cpp_Lecture notes.pptx
CSC2161Programming_in_Cpp_Lecture notes.pptxCSC2161Programming_in_Cpp_Lecture notes.pptx
CSC2161Programming_in_Cpp_Lecture notes.pptx
winebaldbanituze
 
Chapter 1 (2) array and structure r.pptx
Chapter 1 (2) array and structure r.pptxChapter 1 (2) array and structure r.pptx
Chapter 1 (2) array and structure r.pptx
abenezertekalign118
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
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
sarthakgithub
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
C++ Functions.pptx
C++ Functions.pptxC++ Functions.pptx
C++ Functions.pptx
DikshaDani5
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
rebin5725
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
Faizan Janjua
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
bhargavi804095
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
LidetAdmassu
 
Programming Fundamentals lecture-10.pptx
Programming Fundamentals lecture-10.pptxProgramming Fundamentals lecture-10.pptx
Programming Fundamentals lecture-10.pptx
singyali199
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
Chapter 6 - Modular Programming- in C++.pptx
Chapter 6 - Modular Programming- in C++.pptxChapter 6 - Modular Programming- in C++.pptx
Chapter 6 - Modular Programming- in C++.pptx
ChereLemma2
 

More from Ahmad177077 (12)

Pointers in C++ object oriented programming
Pointers in C++ object oriented programmingPointers in C++ object oriented programming
Pointers in C++ object oriented programming
Ahmad177077
 
Array In C++ programming object oriented programming
Array In C++ programming object oriented programmingArray In C++ programming object oriented programming
Array In C++ programming object oriented programming
Ahmad177077
 
Operators in c++ programming types of variables
Operators in c++ programming types of variablesOperators in c++ programming types of variables
Operators in c++ programming types of variables
Ahmad177077
 
2. Variables and Data Types in C++ proramming.pptx
2. Variables and Data Types in C++ proramming.pptx2. Variables and Data Types in C++ proramming.pptx
2. Variables and Data Types in C++ proramming.pptx
Ahmad177077
 
Introduction to c++ programming language
Introduction to c++ programming languageIntroduction to c++ programming language
Introduction to c++ programming language
Ahmad177077
 
Selection Sort & Insertion Sorts Algorithms
Selection Sort & Insertion Sorts AlgorithmsSelection Sort & Insertion Sorts Algorithms
Selection Sort & Insertion Sorts Algorithms
Ahmad177077
 
Strassen's Matrix Multiplication divide and conquere algorithm
Strassen's Matrix Multiplication divide and conquere algorithmStrassen's Matrix Multiplication divide and conquere algorithm
Strassen's Matrix Multiplication divide and conquere algorithm
Ahmad177077
 
Recursive Algorithms with their types and implementation
Recursive Algorithms with their types and implementationRecursive Algorithms with their types and implementation
Recursive Algorithms with their types and implementation
Ahmad177077
 
Graph Theory in Theoretical computer science
Graph Theory in Theoretical computer scienceGraph Theory in Theoretical computer science
Graph Theory in Theoretical computer science
Ahmad177077
 
Propositional Logics in Theoretical computer science
Propositional Logics in Theoretical computer sciencePropositional Logics in Theoretical computer science
Propositional Logics in Theoretical computer science
Ahmad177077
 
Proof Techniques in Theoretical computer Science
Proof Techniques in Theoretical computer ScienceProof Techniques in Theoretical computer Science
Proof Techniques in Theoretical computer Science
Ahmad177077
 
1. Introduction to C++ and brief history
1. Introduction to C++ and brief history1. Introduction to C++ and brief history
1. Introduction to C++ and brief history
Ahmad177077
 
Pointers in C++ object oriented programming
Pointers in C++ object oriented programmingPointers in C++ object oriented programming
Pointers in C++ object oriented programming
Ahmad177077
 
Array In C++ programming object oriented programming
Array In C++ programming object oriented programmingArray In C++ programming object oriented programming
Array In C++ programming object oriented programming
Ahmad177077
 
Operators in c++ programming types of variables
Operators in c++ programming types of variablesOperators in c++ programming types of variables
Operators in c++ programming types of variables
Ahmad177077
 
2. Variables and Data Types in C++ proramming.pptx
2. Variables and Data Types in C++ proramming.pptx2. Variables and Data Types in C++ proramming.pptx
2. Variables and Data Types in C++ proramming.pptx
Ahmad177077
 
Introduction to c++ programming language
Introduction to c++ programming languageIntroduction to c++ programming language
Introduction to c++ programming language
Ahmad177077
 
Selection Sort & Insertion Sorts Algorithms
Selection Sort & Insertion Sorts AlgorithmsSelection Sort & Insertion Sorts Algorithms
Selection Sort & Insertion Sorts Algorithms
Ahmad177077
 
Strassen's Matrix Multiplication divide and conquere algorithm
Strassen's Matrix Multiplication divide and conquere algorithmStrassen's Matrix Multiplication divide and conquere algorithm
Strassen's Matrix Multiplication divide and conquere algorithm
Ahmad177077
 
Recursive Algorithms with their types and implementation
Recursive Algorithms with their types and implementationRecursive Algorithms with their types and implementation
Recursive Algorithms with their types and implementation
Ahmad177077
 
Graph Theory in Theoretical computer science
Graph Theory in Theoretical computer scienceGraph Theory in Theoretical computer science
Graph Theory in Theoretical computer science
Ahmad177077
 
Propositional Logics in Theoretical computer science
Propositional Logics in Theoretical computer sciencePropositional Logics in Theoretical computer science
Propositional Logics in Theoretical computer science
Ahmad177077
 
Proof Techniques in Theoretical computer Science
Proof Techniques in Theoretical computer ScienceProof Techniques in Theoretical computer Science
Proof Techniques in Theoretical computer Science
Ahmad177077
 
1. Introduction to C++ and brief history
1. Introduction to C++ and brief history1. Introduction to C++ and brief history
1. Introduction to C++ and brief history
Ahmad177077
 
Ad

Recently uploaded (20)

How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Ad

6. Functions in C ++ programming object oriented programming

  • 1. 1 Functions in C++ Ahmad Baryal Saba Institute of Higher Education Computer Science Faculty Oct 21, 2024
  • 2. 2 Table of contents  What is function?  Why do we need functions?  Function structure  Function declaration  Types of functions  Function calling  Function call methods  Recursion  Inline Functions  Function overloading
  • 3. 3 Function C++  A function is a set of statements that takes input, does some specific computation, and produces output. The idea is to put some commonly or repeatedly done tasks together to make a function so that instead of writing the same code again and again for different inputs, we can call this function.  They also enable code reusability by allowing you to call a function multiple times within your program.
  • 4. 4 Why Do we Need Functions? • Functions help us in reducing code redundancy. If functionality is performed at multiple places in software, then rather than writing the same code, again and again, we create a function and call it everywhere. This also helps in maintenance as we have to make changes in only one place if we make changes to the functionality in future. • Functions make code modular. Consider a big file having many lines of code. It becomes really simple to read and use the code, if the code is divided into functions. • Functions provide abstraction. For example, we can use library functions without worrying about their internal work.
  • 5. 5 Function structure in c++ Let's break down the components of a C++ function: return_type: This is the data type of the value that the function will return after it has executed its task. If the function doesn't return a value, you can use void as the return type. function_name: This is the name you choose for your function, following the naming rules of C++. parameters: These are optional input values that the function can accept. Parameters are enclosed in parentheses and separated by commas. They allow you to pass information into the function for processing. Function body: This is the actual code that performs the specific task of the function. return (optional): If the return_type is not void, you can use the return statement to send a
  • 6. 6 Function Return Type in C++ The return type is the type of value returned by the function. A function in C++ may or may not return a value. If the function does not return a value then its return type is void. Value is returned from a function using the return statement. Control is transferred back to the caller when the return statement is executed. If the function returns a value then we need to specify its data type, like int, char, or float. Note: Only one value can be returned from a function in C++. It is mandatory to return a value for functions with a non-void return type. For example, consider a function calculateFactorial which calculates the factorial of a number and returns an integer value. We can see its return type is int. int calculateFactorial( int num) { int fact=1; for(int i=1;i<=num;i++) fact*=i; return fact; }
  • 7. 7 Types of Functions 1. User Defined Function are user/customer-defined blocks of code specially customized to reduce the complexity of big programs. They are also commonly known as “tailor-made functions” which are built only to satisfy the condition in which the user is facing issues meanwhile reducing the complexity of the whole program. 2. Library functions are also called “built-in Functions“. These functions are part of a compiler package that is already defined and consists of a special function with special and different meanings. Built-in Function gives us an edge as we can directly use them without defining them whereas in the user-defined function we have to declare and define a function before using them. For Example: sqrt(), sort(),pow(),reverse(),abs(), etc.
  • 8. 8 Calling a Function In C++, you can call a function by specifying the function's name, followed by parentheses containing any necessary arguments (if the function takes parameters). Here's the basic syntax for calling a function in C++: // Function declaration int add(int a, int b); int main() { int result = add(5, 3); // Calling the add function cout << "Result: " << result << endl; return 0; } // Function definition int add(int a, int b) { return a + b; }
  • 9. 9 There are two most popular ways to pass parameters: 1. Pass by Value: In this parameter passing method, values of actual parameters are copied to the function’s formal parameters. The actual and formal parameters are stored in different memory locations so any changes made in the functions are not reflected in the actual parameters of the caller. void incrementByValue(int x) { x++; // Increment the value of x cout << "Inside incrementByValue: x = " << x << endl; } int main() { int num = 5; cout << "Original value of num: " << num << endl; incrementByValue(num); cout << "After incrementByValue: num = " << num << endl; return 0; }
  • 10. 10 There are two most popular ways to pass parameters: 1. Pass by Reference: Both actual and formal parameters refer to the same locations, so any changes made inside the function are reflected in the actual parameters of the caller. void incrementByReference(int &x) { x++; // Increment the value referred to by x cout << "Inside incrementByReference: x = " << x << endl; } int main() { int num = 5; cout << "Original value of num: " << num << endl; incrementByReference(num); cout << "After incrementByReference: num = " << num << endl; return 0; }
  • 11. 11 Difference between call by value and call by reference in C++ Call by value  A copy of the value is passed to the function  Changes made inside the function are not reflected on other functions  Actual and formal arguments will be created at different memory location Call by reference  An address of value is passed to the function  Changes made inside the function are reflected outside the function as well  Actual and formal arguments will be created at same memory location.
  • 12. 12 Recursion in function Recursion is a programming concept where a function calls itself directly or indirectly to solve a problem. #include <iostream> using namespace std; // Recursive factorial function int factorial(int n) { // Base case: factorial of 0 is 1 if (n == 0 || n == 1) { return 1; } else { // Recursive case: n! = n * (n-1)! return n * factorial(n - 1); } } int main() { // Example usage of the factorial function int num = 5; cout << "Factorial of " << num << " is: " << factorial(num) << endl; return 0; }
  • 13. 13 Inline functions Inline functions in C++ are expanded by the compiler directly at the point of the function call, eliminating the overhead of a regular function call. Marked with the inline keyword. Pros: • Performance improvement by reducing function call overhead. • Compiler optimization opportunities. • Reduced time and space overhead on the call stack. Cons: • Potential code bloat due to duplicated code at call sites. • Compiler might choose not to inline based on its optimization criteria. • Can reduce code maintainability for complex functions.
  • 14. 14 Inline functions Example #include <iostream> using namespace std; // Definition of an inline function inline int square(int x) { return x * x; } int main() { int num = 5; // Inline function call int result = square(num); cout << "Square of " << num << " is: " << result << endl; return 0; }
  • 15. 15 Function overloading • Function overloading is a feature in C++ that allows multiple functions in the same scope with the same name but different parameter lists. • It provides a way to create functions that perform similar tasks but with variations in the type or number of parameters. Overloading Based on the Number and Type of Parameters: • Overloaded functions must differ in either the number or type of their parameters. • The compiler determines which function to call based on the number and types of arguments passed during the function call.
  • 16. 16 Example 1: Overloading Based on Number of Parameters: #include <iostream> using namespace std; // Function to add two integers int add(int a, int b) { return a + b; } // Overloaded function to add three integers int add(int a, int b, int c) { return a + b + c; } int main() { cout << "Sum of 2 and 3: " << add(2, 3) << endl; cout << "Sum of 2, 3, and 4: " << add(2, 3, 4) << endl; return 0; }
  • 17. 17 Example 2: Overloading Based on Type of Parameters: #include <iostream> using namespace std; // Function to add two integers int add(int a, int b) { return a + b; } // Overloaded function to concatenate two strings string add(const string& str1, const string& str2) { return str1 + str2; } int main() { cout << "Sum of 2 and 3: " << add(2, 3) << endl; cout << "Concatenation of 'Hello' and ' World': " << add("Hello", " World") << endl; return 0; }
  • 18. 18 Functions Using Pointers The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value at the address ptr. The dereference operator * is used to access the value at an address. In the statement ‘*ptr = 30’, the value at address ptr is changed to 30. The address operator & is used to get the address of a variable of any data type. In the function call statement ‘fun(&x)’, the address of x is passed so that x can be modified using its address. // C++ Program to demonstrate working of // function using pointers #include <iostream> using namespace std; void fun(int* ptr) { *ptr = 30; } int main() { int x = 20; fun(&x); cout << "x = " << x; return 0;