SlideShare a Scribd company logo
C++ Functions
Main () function
C++ functions are a group of statements in a single logical unit
to perform some specific task.
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello world!";
return 0;
}
Structure of main () function
Function Header
Return type
In this case,
integer
Function_name,
main
Argument/s ( )
In this case, void
Entry Point, Curly braces
Exit Point, Curly braces
Return statement
Function
Body
Statement 1…
Statement 2…
……………..
Note: main () structure defined above extends for all functions
Defining a function
The function header and body together are referred to as the function definition. A function cannot
execute until it is first defined. Once defined, a function executes when it is called.
#include <iostream>
using namespace std;
// begins definition of printMessage function
void printMessage (void)
{ // Statements
cout << "Hello world!";
// return;
}
// ends definition of printMessage function
int main ()
{
printMessage(); // calls printMessage function
return 0;
}
Function Definition
User-defined function
(Header)
No return
Value
Function_name No arguments/parameters
Or simply ( )
Function body
Main Function
#include <iostream>
using namespace std;
void printMessage (void)
{
cout << "Hello world!";
return; //It makes no difference
}
int main ()
{
printMessage();
// calls printMessage function
return 0;
}
Code
Output
Calling a function
A function must be defined first, before it can be called. Unless a function is called, it lies dormant with in
the program. A function can be called from with in main function (or any other function) followed by a
semicolon. { function_name(); }
#include <iostream>
using namespace std;
void sum ()
{
int a,b;
cout << "Addition of 2 numbers!n";
cout << "Enter the 2 numbers...n";
cin >> a >> b;
cout << a << " + " << b << " = "
<< a + b;
return;
}
int main ()
{
sum();
// calls sum() function
return 0;
}
Code Output/s
User Defined Function
Function Header
No return
value
Function_name Function
arguments (none)
Function Body
Main () Function
Function being called from main() body. A
function is called by its name followed by a
semicolon
Order of Execution for a Multi-function program
The order of execution is as follows:
1. Execution always starts with the
main function.
2. The first statement in main,
printMessage(), is executed.
3. Execution next shifts to the
printMessage function, and begins
with the first statement in that
function, which outputs “Hello
world!”
4. After the printMessage function
completes executing, execution
returns to the main function with
the next unexecuted statement,
return 0, which completes the main
function.
Function Prototyping
A function prototype is a function declaration that specifies the data types of its arguments in the parameter list. The compiler
uses the information in a function prototype to verify it later when it is defined.
#include <iostream>
using namespace std;
int main ()
{
printMessage();
// calls printMessage function
return 0;
}
void printMessage (void)
{
cout << "Hello world!";
return;
}
Code •Since Execution always begins from main(), why isn’t it placed in the beginning of program
syntax as shown in the code on the left?
•However If we run this code, the compiler gives an error “undeclared identifier”.
•The reason being that since compiler runs from top to bottom & always executes from the
main (), as it encounters the printmessage() function call, it generates error. Because it must
already know of the function’s name, return type, & arguments.
•The preferred solution is to prototype every function (except main ofcourse).
•After prototyping (typing function header followed by ;) above the main function!The
program runs just fine.!
•Output:
•But why should we prototype?
void printMessage (void);
//function prototype
Scope of a variable
Local
Variables
So far all variables have been defined
within main function. In programs
where the only function is main, those
variables can be accessed throughout
the entire program since main is the
entire program. However, once we start
dividing up the code into separate
functions, issues arise.
•The portion of the program where an
identifier can be used is known as its scope.
For example, when we declare a local variable
in a block, it can be referenced only in that
block and in blocks nested within that block.
•The life of a local variable ends (It is
destroyed) when the function exits.
LocalVariable
#include <iostream>
using namespace std;
void test(); Function Prototype( indicates there is 1 function besides main)
int main()
{
// local variable to main()
int var = 5; Variable defined in the locality of main
test(); Function Call
// illegal: var1 not declared inside main()
var1 = 9; // error – undefined identifier
}
void test()
{
// local variable to test()
int var1;
var1 = 6;
// illegal: var not declared inside test()
cout << var; //error – undefined identifier
}
Main Function
Test Function
•The portion of the program where an
identifier can be used is known as its scope.
However if a variable is declared above all
functions & their prototypes, then that
variable scopes to the whole of the program.
•It is accessible anywhere through out the
program.
•The life of a local variable ends (It is
destroyed) when the program itself exits.
GlobalVariable
#include <iostream>
using namespace std;
// Global variable declaration
int c = 12;
void test();
int main()
{
++c; // global variable(accessible)
// Outputs 13
cout << c <<endl;
test();
return 0;
}
void test()
{
++c; // global variable (accessible)
// Outputs 14
cout << c;
}
GlobalVariable (Variable identified by all
function throughout the program.)
Function Call
So far, we have passed none arguments to the function. Hence we used void function_name (void) type.
Sending Information to a function
There are 2 methods for passing
arguments!
• Passing by reference. (It makes
use of addresses & pointers),
Thus we will study it later.
• Passing by value. In this method,
a value (in constant or variable
form) is passed as an argument to
the function, It then manipulates
it according to program.
• OUTPUT:
#include <iostream>
#include <cmath> // Math function Library
using namespace std; // standard namespace
void circle (double); // function prototype (only data-types)
double PI = 3.1415; // Global Variable
int main() // Main () Header
{ // Main () body entry brace
double rad; // Local variable (rad)
cout << "Solving for the circumference “
<< "& Area of the Circle." << endl;
cout << "...............................n";
cout << "Enter the radius! n";
cin >> rad; // Initializing the local variable (rad)
cout << "...............................n";
circle(rad); // Passing the value to circle() as argument
return 0; // Program exit code
} // Main () body exit brace
void circle (double r) // circle () Header with one double type argument
{ // circle () body entry brace
cout << "Circumference of circle = "
<< 2*PI*r << endl; // Circumference displayed
cout << "Area of the circle = "
<< PI * pow(r,2) << endl; // pow(r,2) is builtin function from math lib
return;
} // circle () body exit brace
Sending Multiple Arguments to a function
#include <iostream>
using namespace std; // standard namespace
void rectangle (double, double);
// function prototype (only data-types)
int main() // Main () Header
{ // Main () body entry brace
double len,wid; // Local variables(len,wid)
cout << "Solving for the Perimeter "
<< "& Area of the rectangle." << endl;
cout << "...............................n";
cout << "Enter the Length & width values! n";
cin >> len >> wid; // Initializing the local variables
cout << "...............................n";
rectangle(len,wid); // Passing the values to rectangle() as
arguments
return 0; // Program exit code
} // Main () body exit brace
void rectangle (double l,double w) // rectangle () Header
{ // rectangle () body entry brace
cout << "Perimeter of rectangle = "
<< 2*(l+w) << endl; // Perimeter displayed
cout << "Area of the circle = "
<< l*w << endl; // Area displayed
return;
} // rectangle () body exit brace
A function can receive multiple arguments
as well.
e.g.
1. rectangle(len,wid);
2. rectangle(14.5,78);
3. sum(3,4,6);
4. Avg(num1,num2,………..num_n)
ReturnValue from a function
#include <iostream>
using namespace std;
double Avg (double,double,double); //function prototype
int main() // main () header
{
double a,b,c; // Local variables to main()
cout << "Solving for Average of 3 numbers!"
<< endl << "Enter the 3 numbers!n";
cin >> a >> b >> c; // Local var initialization
double ans = Avg(a,b,c); // function call with a
return value
// stored in double variable ans
cout << "Answer = "<< ans; // display ans
}
double Avg (double n1,double n2,double n3) // Avg
function header
{
return (n1+n2+n3)/3; // return statement for Avg()
}
C++ Functions
Types of Function Calling
1
Accepting Parameter and Returning Value
2
Accepting Parameter and not Returning Value
Types of Function Calling (Continued)
4
Not Accepting Parameter & not Returning Value
3
Not Accepting Parameter but Returning Value
TO BE CONTINUED

More Related Content

PPTX
Inline function
PDF
Function in C++
PDF
Chapter 11 Function
PPTX
Inline assembly language programs in c
PPTX
Functions1
PPT
85ec7 session2 c++
PPTX
Function Parameters
PPTX
INLINE FUNCTION IN C++
Inline function
Function in C++
Chapter 11 Function
Inline assembly language programs in c
Functions1
85ec7 session2 c++
Function Parameters
INLINE FUNCTION IN C++

What's hot (20)

PPTX
Inline Functions and Default arguments
PDF
Booting into functional programming
PPTX
Inline functions
PDF
How To Use IO Monads in Scala?
PDF
(3) cpp procedural programming
PDF
Intro to JavaScript - Week 2: Function
PPTX
Python Programming Essentials - M25 - os and sys modules
ODP
C++ Function
PPTX
Operator overloading
PDF
Php, mysq lpart3
PPTX
A Brief Conceptual Introduction to Functional Java 8 and its API
PPT
Operator overloading
PDF
Kotlin으로 안드로이드 개발하기
PDF
iOS Selectors Blocks and Delegation
PPTX
Operator overloading
PDF
iOS: Frameworks and Delegation
PDF
AnyObject – 自分が見落としていた、基本の話
KEY
What's New In Python 2.4
PPTX
Operator overloading
Inline Functions and Default arguments
Booting into functional programming
Inline functions
How To Use IO Monads in Scala?
(3) cpp procedural programming
Intro to JavaScript - Week 2: Function
Python Programming Essentials - M25 - os and sys modules
C++ Function
Operator overloading
Php, mysq lpart3
A Brief Conceptual Introduction to Functional Java 8 and its API
Operator overloading
Kotlin으로 안드로이드 개발하기
iOS Selectors Blocks and Delegation
Operator overloading
iOS: Frameworks and Delegation
AnyObject – 自分が見落としていた、基本の話
What's New In Python 2.4
Operator overloading
Ad

Similar to C++ Functions (20)

PPT
Chapter Introduction to Modular Programming.ppt
PPT
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
PPT
Functions
PPTX
Part 3-functions1-120315220356-phpapp01
PPTX
Chapter 4
PPT
User Defined Functions
PPTX
Amit user defined functions xi (2)
PPTX
Function C++
PPTX
Cs1123 8 functions
PPTX
Intro To C++ - Class #19: Functions
PPT
POLITEKNIK MALAYSIA
DOCX
Functions assignment
DOCX
Introduction to c programming
DOC
Functions
PDF
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
PDF
concept of functions and its types in c++ language
PPT
Functions in c++
PPT
Lecture 4
PPT
C++ Functions.ppt
PDF
Functionssssssssssssssssssssssssssss.pdf
Chapter Introduction to Modular Programming.ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
Functions
Part 3-functions1-120315220356-phpapp01
Chapter 4
User Defined Functions
Amit user defined functions xi (2)
Function C++
Cs1123 8 functions
Intro To C++ - Class #19: Functions
POLITEKNIK MALAYSIA
Functions assignment
Introduction to c programming
Functions
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
concept of functions and its types in c++ language
Functions in c++
Lecture 4
C++ Functions.ppt
Functionssssssssssssssssssssssssssss.pdf
Ad

Recently uploaded (20)

PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PPTX
OOP with Java - Java Introduction (Basics)
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
additive manufacturing of ss316l using mig welding
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
DOCX
573137875-Attendance-Management-System-original
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Welding lecture in detail for understanding
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Arduino robotics embedded978-1-4302-3184-4.pdf
OOP with Java - Java Introduction (Basics)
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
CH1 Production IntroductoryConcepts.pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
additive manufacturing of ss316l using mig welding
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
573137875-Attendance-Management-System-original
Mechanical Engineering MATERIALS Selection
Welding lecture in detail for understanding
Strings in CPP - Strings in C++ are sequences of characters used to store and...
Foundation to blockchain - A guide to Blockchain Tech
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Operating System & Kernel Study Guide-1 - converted.pdf

C++ Functions

  • 2. Main () function C++ functions are a group of statements in a single logical unit to perform some specific task. #include <iostream> using namespace std; int main () { cout << "Hello world!"; return 0; } Structure of main () function Function Header Return type In this case, integer Function_name, main Argument/s ( ) In this case, void Entry Point, Curly braces Exit Point, Curly braces Return statement Function Body Statement 1… Statement 2… …………….. Note: main () structure defined above extends for all functions
  • 3. Defining a function The function header and body together are referred to as the function definition. A function cannot execute until it is first defined. Once defined, a function executes when it is called. #include <iostream> using namespace std; // begins definition of printMessage function void printMessage (void) { // Statements cout << "Hello world!"; // return; } // ends definition of printMessage function int main () { printMessage(); // calls printMessage function return 0; } Function Definition User-defined function (Header) No return Value Function_name No arguments/parameters Or simply ( ) Function body Main Function #include <iostream> using namespace std; void printMessage (void) { cout << "Hello world!"; return; //It makes no difference } int main () { printMessage(); // calls printMessage function return 0; } Code Output
  • 4. Calling a function A function must be defined first, before it can be called. Unless a function is called, it lies dormant with in the program. A function can be called from with in main function (or any other function) followed by a semicolon. { function_name(); } #include <iostream> using namespace std; void sum () { int a,b; cout << "Addition of 2 numbers!n"; cout << "Enter the 2 numbers...n"; cin >> a >> b; cout << a << " + " << b << " = " << a + b; return; } int main () { sum(); // calls sum() function return 0; } Code Output/s User Defined Function Function Header No return value Function_name Function arguments (none) Function Body Main () Function Function being called from main() body. A function is called by its name followed by a semicolon
  • 5. Order of Execution for a Multi-function program The order of execution is as follows: 1. Execution always starts with the main function. 2. The first statement in main, printMessage(), is executed. 3. Execution next shifts to the printMessage function, and begins with the first statement in that function, which outputs “Hello world!” 4. After the printMessage function completes executing, execution returns to the main function with the next unexecuted statement, return 0, which completes the main function.
  • 6. Function Prototyping A function prototype is a function declaration that specifies the data types of its arguments in the parameter list. The compiler uses the information in a function prototype to verify it later when it is defined. #include <iostream> using namespace std; int main () { printMessage(); // calls printMessage function return 0; } void printMessage (void) { cout << "Hello world!"; return; } Code •Since Execution always begins from main(), why isn’t it placed in the beginning of program syntax as shown in the code on the left? •However If we run this code, the compiler gives an error “undeclared identifier”. •The reason being that since compiler runs from top to bottom & always executes from the main (), as it encounters the printmessage() function call, it generates error. Because it must already know of the function’s name, return type, & arguments. •The preferred solution is to prototype every function (except main ofcourse). •After prototyping (typing function header followed by ;) above the main function!The program runs just fine.! •Output: •But why should we prototype? void printMessage (void); //function prototype
  • 7. Scope of a variable Local Variables So far all variables have been defined within main function. In programs where the only function is main, those variables can be accessed throughout the entire program since main is the entire program. However, once we start dividing up the code into separate functions, issues arise.
  • 8. •The portion of the program where an identifier can be used is known as its scope. For example, when we declare a local variable in a block, it can be referenced only in that block and in blocks nested within that block. •The life of a local variable ends (It is destroyed) when the function exits. LocalVariable #include <iostream> using namespace std; void test(); Function Prototype( indicates there is 1 function besides main) int main() { // local variable to main() int var = 5; Variable defined in the locality of main test(); Function Call // illegal: var1 not declared inside main() var1 = 9; // error – undefined identifier } void test() { // local variable to test() int var1; var1 = 6; // illegal: var not declared inside test() cout << var; //error – undefined identifier } Main Function Test Function
  • 9. •The portion of the program where an identifier can be used is known as its scope. However if a variable is declared above all functions & their prototypes, then that variable scopes to the whole of the program. •It is accessible anywhere through out the program. •The life of a local variable ends (It is destroyed) when the program itself exits. GlobalVariable #include <iostream> using namespace std; // Global variable declaration int c = 12; void test(); int main() { ++c; // global variable(accessible) // Outputs 13 cout << c <<endl; test(); return 0; } void test() { ++c; // global variable (accessible) // Outputs 14 cout << c; } GlobalVariable (Variable identified by all function throughout the program.) Function Call
  • 10. So far, we have passed none arguments to the function. Hence we used void function_name (void) type. Sending Information to a function There are 2 methods for passing arguments! • Passing by reference. (It makes use of addresses & pointers), Thus we will study it later. • Passing by value. In this method, a value (in constant or variable form) is passed as an argument to the function, It then manipulates it according to program. • OUTPUT: #include <iostream> #include <cmath> // Math function Library using namespace std; // standard namespace void circle (double); // function prototype (only data-types) double PI = 3.1415; // Global Variable int main() // Main () Header { // Main () body entry brace double rad; // Local variable (rad) cout << "Solving for the circumference “ << "& Area of the Circle." << endl; cout << "...............................n"; cout << "Enter the radius! n"; cin >> rad; // Initializing the local variable (rad) cout << "...............................n"; circle(rad); // Passing the value to circle() as argument return 0; // Program exit code } // Main () body exit brace void circle (double r) // circle () Header with one double type argument { // circle () body entry brace cout << "Circumference of circle = " << 2*PI*r << endl; // Circumference displayed cout << "Area of the circle = " << PI * pow(r,2) << endl; // pow(r,2) is builtin function from math lib return; } // circle () body exit brace
  • 11. Sending Multiple Arguments to a function #include <iostream> using namespace std; // standard namespace void rectangle (double, double); // function prototype (only data-types) int main() // Main () Header { // Main () body entry brace double len,wid; // Local variables(len,wid) cout << "Solving for the Perimeter " << "& Area of the rectangle." << endl; cout << "...............................n"; cout << "Enter the Length & width values! n"; cin >> len >> wid; // Initializing the local variables cout << "...............................n"; rectangle(len,wid); // Passing the values to rectangle() as arguments return 0; // Program exit code } // Main () body exit brace void rectangle (double l,double w) // rectangle () Header { // rectangle () body entry brace cout << "Perimeter of rectangle = " << 2*(l+w) << endl; // Perimeter displayed cout << "Area of the circle = " << l*w << endl; // Area displayed return; } // rectangle () body exit brace A function can receive multiple arguments as well. e.g. 1. rectangle(len,wid); 2. rectangle(14.5,78); 3. sum(3,4,6); 4. Avg(num1,num2,………..num_n)
  • 12. ReturnValue from a function #include <iostream> using namespace std; double Avg (double,double,double); //function prototype int main() // main () header { double a,b,c; // Local variables to main() cout << "Solving for Average of 3 numbers!" << endl << "Enter the 3 numbers!n"; cin >> a >> b >> c; // Local var initialization double ans = Avg(a,b,c); // function call with a return value // stored in double variable ans cout << "Answer = "<< ans; // display ans } double Avg (double n1,double n2,double n3) // Avg function header { return (n1+n2+n3)/3; // return statement for Avg() }
  • 14. Types of Function Calling 1 Accepting Parameter and Returning Value 2 Accepting Parameter and not Returning Value
  • 15. Types of Function Calling (Continued) 4 Not Accepting Parameter & not Returning Value 3 Not Accepting Parameter but Returning Value

Editor's Notes

  • #4: Let’s take our “Hello World” example and divide the code into two functions, main and a printMessage function that outputs “Hello world!” The body of the printMessage function has one statement, which outputs “Hello world!” The function body does not need to contain an explicit return statement because, since the return type is void, the return statement is implied. However, you may include an explicit return statement.