SlideShare a Scribd company logo
1 of 24
A First Book of C++A First Book of C++
Chapter 6Chapter 6
Modularity Using FunctionsModularity Using Functions
(Part 1)(Part 1)
∗ In this chapter, you will learn about:
∗ Function and Parameter Declarations
∗ Returning a Single Value
∗ Returning Multiple Values
∗ Variable Scope
∗ Variable Storage Class
∗ Common Programming Errors
∗ Generating Random Numbers
A First Book of C++ 4th Edition 2
Objectives
∗ All C++ programs must contain a main() function
∗ May also contain unlimited additional functions
∗ Major programming concerns when creating
functions:
∗ How does a function interact with other functions
(including main)?
∗ Correctly passing data to function
∗ Correctly returning values from a function
A First Book of C++ 4th Edition 3
Function and Parameter Declarations
∗ Function call process:
∗ Give function name
∗ Pass data to function as arguments in parentheses
following function name
∗ Only after called function receives data successfully
can the data be manipulated within the function
A First Book of C++ 4th Edition 4
Function and Parameter Declarations
(cont'd.)
Function and Parameter Declarations
(cont'd.)
A First Book of C++ 4th Edition 5
header line void sum (int a, int b) pow(x,2)
{
}
arguments (inputs/data passed to function)
A First Book of C++ 4th Edition 6
Function and Parameter Declarations
(cont'd.)
∗ Program 6.1 not complete
∗ The function findMax() must be written and
added
∗ Done in slide 15
∗ Complete program components:
∗ main(): referred to as calling function (the one that
calls)
∗ findMax(): referred to as called function (the one
being called)
∗ Complete program can be compiled and executed
A First Book of C++ 4th Edition 7
Function and Parameter Declarations
(cont'd.)
∗ Function prototype: declaration statement for a
function
∗ Before a function can be called, it must be declared to
the calling function (just like variable declaration)
∗ Provides the calling function with the following info:
∗ The type of value to be returned, if any
∗ The data type and order of values the calling function
should transmit/pass to the called function
A First Book of C++ 4th Edition 8
Function Prototypes
∗ Example: the function prototype in Program 6.1
void findMax(int, int);
∗ Declares that findMax() expects two integer values
sent to it
∗ findMax() returns no value * void means None
∗ Prototype statement placement options:
∗ Together with variable declaration statements just above
calling function name (as in Program 6.1)
∗ In a separate header file to be included using a #include
preprocessor statement
A First Book of C++ 4th Edition 9
Function Prototypes (cont'd.)
A First Book of C++ 4th Edition 10
Calling a Function (Program 6.1)
A First Book of C++ 4th Edition 11
Calling a Function (cont'd.)
∗ A function is defined when it is written
∗ Can then be used by any other function that suitably
declares it
∗ Format: two parts
∗ Function header identifies:
∗ Data type returned by the function
∗ Function name
∗ Number, order, and type of arguments expected by the
function
∗ Function body: statements that operate on data
∗ Returns one value back to the calling function
A First Book of C++ 4th Edition 12
Defining a Function
A First Book of C++ 4th Edition 13
Defining a Function (cont'd.)
A First Book of C++ 4th Edition 14
A First Book of C++ 4th Edition 15
Defining a Function (cont'd.)
//function header
void findMax (int x, int y) // x = firstnum , y = secnum
{ // start of function body
int maxnum; // variable declaration
if (x >= y) // find the maximum between 2 numbers
maxnum = x;
else
maxnum = y;
cout << "nThe maximum of the two numbers is "
<<maxnum << endl;
return;
} // end of function body and end of function
∗ Order of functions in a program:
∗ Any order is allowed
∗ main() usually first
∗ main() is the driver function
∗ Gives reader overall program concept before details of each
function encountered
∗ Each function defined outside any other function
∗ Each function is separate and independent
∗ Nesting functions is never permitted (no nested function)
A First Book of C++ 4th Edition 16
Defining a Function (cont'd.)
∗ Requirement: items that must be either declared or
defined before they are used:
∗ Preprocessor directives
∗ Named constants
∗ Variables
∗ Functions
∗ Otherwise, C++ is flexible in requirements for ordering
of statements
A First Book of C++ 4th Edition 17
Placement of Statements
∗ Recommended ordering of statements
∗ Good programming practice
A First Book of C++ 4th Edition 18
Placement of Statements
(cont'd.)
preprocessor directives
function prototypes
int main()
{
// symbolic constants
// variable declarations
// other executable statements
// return value
}
// function definitions
∗ Possible programming approach:
∗ Write main() first and add functions as developed
∗ Program cannot be run until all functions are included
∗ Stub: beginning of a final function
∗ Can be used as a placeholder for a function until the
function is completed
∗ A “fake” function that accepts parameters and returns
values in proper form (incomplete but working)
∗ Allows main to be compiled and tested before all
functions are completed
A First Book of C++ 4th Edition 19
Function Stubs
∗ Extremely limited use
∗ Prototype format:
int display ();
int display (void);
∗ Information provided in above prototypes:
∗ display takes no parameters
∗ display returns an integer
A First Book of C++ 4th Edition 20
Functions with Empty Parameter
Lists
∗ Values listed in function prototype
∗ Automatically transmitted to the called function when the
arguments are omitted from function call
∗ Example (prototype):
void example (int, int = 5, double = 6.78);
∗ Provides default values for last two arguments
∗ Following function calls are valid:
example(7, 2, 9.3) // no defaults used
example(7, 2) // same as example(7, 2, 6.78)
example(7) // same as example(7, 5, 6.78)
A First Book of C++ 4th Edition 21
Default Arguments
∗ Function overloading: using same function name for more
than one function
∗ Compiler must be able to determine which function to use
based on data types of parameters (not data type of return
value)
∗ Each function must be written separately
∗ Each exists as a separate entity
∗ Use of same name does not require code to be similar
∗ Good programming practice: functions with the same name
perform similar operations
A First Book of C++ 4th Edition 22
Reusing Function Names
(Overloading)
Example: two functions named cdabs()
void cdabs(int x) // compute and display the abs. value of integer
{
if ( x < 0 )
x = -x;
cout << "The absolute value of the integer is " << x << endl;
}
void cdabs(float x) //compute and display the abs. value of float
{
if ( x < 0 )
x = -x;
cout << "The absolute value of the float is " << x << endl;
}
A First Book of C++ 4th Edition 23
Reusing Function Names
(Overloading) (cont'd.)
∗ Function call: cdabs(10);
∗ Causes compiler to use the function named cdabs()
that expects and integer argument
∗ Function call: cdabs(6.28f);
∗ Causes compiler to use the function named cdabs()
that expects a double-precision argument
∗ Major use of overloaded functions
∗ Constructor functions
A First Book of C++ 4th Edition 24
Reusing Function Names
(Overloading) (cont'd.)

More Related Content

What's hot (20)

Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
C++ ch2
C++ ch2C++ ch2
C++ ch2
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
C++ Ch3
C++ Ch3C++ Ch3
C++ Ch3
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
C++11
C++11C++11
C++11
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
C formatted and unformatted input and output constructs
C  formatted and unformatted input and output constructsC  formatted and unformatted input and output constructs
C formatted and unformatted input and output constructs
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
Array strings
Array stringsArray strings
Array strings
 
stack
stackstack
stack
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
C language presentation
C language presentationC language presentation
C language presentation
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
Labsheet1stud
Labsheet1studLabsheet1stud
Labsheet1stud
 
First program of C ( Complete Explanation )
First program of C ( Complete Explanation )First program of C ( Complete Explanation )
First program of C ( Complete Explanation )
 

Similar to C++ Functions Guide

Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpuDhaval Jalalpara
 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)Arpit Meena
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
 
C Programming ppt for beginners . Introduction
C Programming ppt for beginners . IntroductionC Programming ppt for beginners . Introduction
C Programming ppt for beginners . Introductionraghukatagall2
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1IIUM
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1IIUM
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptxRhishav Poudyal
 

Similar to C++ Functions Guide (20)

Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Function
FunctionFunction
Function
 
Cpp functions
Cpp functionsCpp functions
Cpp functions
 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
 
Functions
FunctionsFunctions
Functions
 
Cpp
CppCpp
Cpp
 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
C Programming ppt for beginners . Introduction
C Programming ppt for beginners . IntroductionC Programming ppt for beginners . Introduction
C Programming ppt for beginners . Introduction
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
User defined functions.1
User defined functions.1User defined functions.1
User defined functions.1
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 

More from IIUM

How to use_000webhost
How to use_000webhostHow to use_000webhost
How to use_000webhostIIUM
 
Chapter 2
Chapter 2Chapter 2
Chapter 2IIUM
 
Chapter 1
Chapter 1Chapter 1
Chapter 1IIUM
 
Kreydle internship-multimedia
Kreydle internship-multimediaKreydle internship-multimedia
Kreydle internship-multimediaIIUM
 
03phpbldgblock
03phpbldgblock03phpbldgblock
03phpbldgblockIIUM
 
Chap2 practice key
Chap2 practice keyChap2 practice key
Chap2 practice keyIIUM
 
Group p1
Group p1Group p1
Group p1IIUM
 
Tutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seoTutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seoIIUM
 
Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009IIUM
 
03 the htm_lforms
03 the htm_lforms03 the htm_lforms
03 the htm_lformsIIUM
 
Exercise on algo analysis answer
Exercise on algo analysis   answerExercise on algo analysis   answer
Exercise on algo analysis answerIIUM
 
Redo midterm
Redo midtermRedo midterm
Redo midtermIIUM
 
Heaps
HeapsHeaps
HeapsIIUM
 
Report format
Report formatReport format
Report formatIIUM
 
Edpuzzle guidelines
Edpuzzle guidelinesEdpuzzle guidelines
Edpuzzle guidelinesIIUM
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam PaperIIUM
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam PaperIIUM
 
Group assignment 1 s21516
Group assignment 1 s21516Group assignment 1 s21516
Group assignment 1 s21516IIUM
 
Avl tree-rotations
Avl tree-rotationsAvl tree-rotations
Avl tree-rotationsIIUM
 
Week12 graph
Week12   graph Week12   graph
Week12 graph IIUM
 

More from IIUM (20)

How to use_000webhost
How to use_000webhostHow to use_000webhost
How to use_000webhost
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Kreydle internship-multimedia
Kreydle internship-multimediaKreydle internship-multimedia
Kreydle internship-multimedia
 
03phpbldgblock
03phpbldgblock03phpbldgblock
03phpbldgblock
 
Chap2 practice key
Chap2 practice keyChap2 practice key
Chap2 practice key
 
Group p1
Group p1Group p1
Group p1
 
Tutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seoTutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seo
 
Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009
 
03 the htm_lforms
03 the htm_lforms03 the htm_lforms
03 the htm_lforms
 
Exercise on algo analysis answer
Exercise on algo analysis   answerExercise on algo analysis   answer
Exercise on algo analysis answer
 
Redo midterm
Redo midtermRedo midterm
Redo midterm
 
Heaps
HeapsHeaps
Heaps
 
Report format
Report formatReport format
Report format
 
Edpuzzle guidelines
Edpuzzle guidelinesEdpuzzle guidelines
Edpuzzle guidelines
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam Paper
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam Paper
 
Group assignment 1 s21516
Group assignment 1 s21516Group assignment 1 s21516
Group assignment 1 s21516
 
Avl tree-rotations
Avl tree-rotationsAvl tree-rotations
Avl tree-rotations
 
Week12 graph
Week12   graph Week12   graph
Week12 graph
 

C++ Functions Guide

  • 1. A First Book of C++A First Book of C++ Chapter 6Chapter 6 Modularity Using FunctionsModularity Using Functions (Part 1)(Part 1)
  • 2. ∗ In this chapter, you will learn about: ∗ Function and Parameter Declarations ∗ Returning a Single Value ∗ Returning Multiple Values ∗ Variable Scope ∗ Variable Storage Class ∗ Common Programming Errors ∗ Generating Random Numbers A First Book of C++ 4th Edition 2 Objectives
  • 3. ∗ All C++ programs must contain a main() function ∗ May also contain unlimited additional functions ∗ Major programming concerns when creating functions: ∗ How does a function interact with other functions (including main)? ∗ Correctly passing data to function ∗ Correctly returning values from a function A First Book of C++ 4th Edition 3 Function and Parameter Declarations
  • 4. ∗ Function call process: ∗ Give function name ∗ Pass data to function as arguments in parentheses following function name ∗ Only after called function receives data successfully can the data be manipulated within the function A First Book of C++ 4th Edition 4 Function and Parameter Declarations (cont'd.)
  • 5. Function and Parameter Declarations (cont'd.) A First Book of C++ 4th Edition 5 header line void sum (int a, int b) pow(x,2) { } arguments (inputs/data passed to function)
  • 6. A First Book of C++ 4th Edition 6 Function and Parameter Declarations (cont'd.)
  • 7. ∗ Program 6.1 not complete ∗ The function findMax() must be written and added ∗ Done in slide 15 ∗ Complete program components: ∗ main(): referred to as calling function (the one that calls) ∗ findMax(): referred to as called function (the one being called) ∗ Complete program can be compiled and executed A First Book of C++ 4th Edition 7 Function and Parameter Declarations (cont'd.)
  • 8. ∗ Function prototype: declaration statement for a function ∗ Before a function can be called, it must be declared to the calling function (just like variable declaration) ∗ Provides the calling function with the following info: ∗ The type of value to be returned, if any ∗ The data type and order of values the calling function should transmit/pass to the called function A First Book of C++ 4th Edition 8 Function Prototypes
  • 9. ∗ Example: the function prototype in Program 6.1 void findMax(int, int); ∗ Declares that findMax() expects two integer values sent to it ∗ findMax() returns no value * void means None ∗ Prototype statement placement options: ∗ Together with variable declaration statements just above calling function name (as in Program 6.1) ∗ In a separate header file to be included using a #include preprocessor statement A First Book of C++ 4th Edition 9 Function Prototypes (cont'd.)
  • 10. A First Book of C++ 4th Edition 10 Calling a Function (Program 6.1)
  • 11. A First Book of C++ 4th Edition 11 Calling a Function (cont'd.)
  • 12. ∗ A function is defined when it is written ∗ Can then be used by any other function that suitably declares it ∗ Format: two parts ∗ Function header identifies: ∗ Data type returned by the function ∗ Function name ∗ Number, order, and type of arguments expected by the function ∗ Function body: statements that operate on data ∗ Returns one value back to the calling function A First Book of C++ 4th Edition 12 Defining a Function
  • 13. A First Book of C++ 4th Edition 13 Defining a Function (cont'd.)
  • 14. A First Book of C++ 4th Edition 14
  • 15. A First Book of C++ 4th Edition 15 Defining a Function (cont'd.) //function header void findMax (int x, int y) // x = firstnum , y = secnum { // start of function body int maxnum; // variable declaration if (x >= y) // find the maximum between 2 numbers maxnum = x; else maxnum = y; cout << "nThe maximum of the two numbers is " <<maxnum << endl; return; } // end of function body and end of function
  • 16. ∗ Order of functions in a program: ∗ Any order is allowed ∗ main() usually first ∗ main() is the driver function ∗ Gives reader overall program concept before details of each function encountered ∗ Each function defined outside any other function ∗ Each function is separate and independent ∗ Nesting functions is never permitted (no nested function) A First Book of C++ 4th Edition 16 Defining a Function (cont'd.)
  • 17. ∗ Requirement: items that must be either declared or defined before they are used: ∗ Preprocessor directives ∗ Named constants ∗ Variables ∗ Functions ∗ Otherwise, C++ is flexible in requirements for ordering of statements A First Book of C++ 4th Edition 17 Placement of Statements
  • 18. ∗ Recommended ordering of statements ∗ Good programming practice A First Book of C++ 4th Edition 18 Placement of Statements (cont'd.) preprocessor directives function prototypes int main() { // symbolic constants // variable declarations // other executable statements // return value } // function definitions
  • 19. ∗ Possible programming approach: ∗ Write main() first and add functions as developed ∗ Program cannot be run until all functions are included ∗ Stub: beginning of a final function ∗ Can be used as a placeholder for a function until the function is completed ∗ A “fake” function that accepts parameters and returns values in proper form (incomplete but working) ∗ Allows main to be compiled and tested before all functions are completed A First Book of C++ 4th Edition 19 Function Stubs
  • 20. ∗ Extremely limited use ∗ Prototype format: int display (); int display (void); ∗ Information provided in above prototypes: ∗ display takes no parameters ∗ display returns an integer A First Book of C++ 4th Edition 20 Functions with Empty Parameter Lists
  • 21. ∗ Values listed in function prototype ∗ Automatically transmitted to the called function when the arguments are omitted from function call ∗ Example (prototype): void example (int, int = 5, double = 6.78); ∗ Provides default values for last two arguments ∗ Following function calls are valid: example(7, 2, 9.3) // no defaults used example(7, 2) // same as example(7, 2, 6.78) example(7) // same as example(7, 5, 6.78) A First Book of C++ 4th Edition 21 Default Arguments
  • 22. ∗ Function overloading: using same function name for more than one function ∗ Compiler must be able to determine which function to use based on data types of parameters (not data type of return value) ∗ Each function must be written separately ∗ Each exists as a separate entity ∗ Use of same name does not require code to be similar ∗ Good programming practice: functions with the same name perform similar operations A First Book of C++ 4th Edition 22 Reusing Function Names (Overloading)
  • 23. Example: two functions named cdabs() void cdabs(int x) // compute and display the abs. value of integer { if ( x < 0 ) x = -x; cout << "The absolute value of the integer is " << x << endl; } void cdabs(float x) //compute and display the abs. value of float { if ( x < 0 ) x = -x; cout << "The absolute value of the float is " << x << endl; } A First Book of C++ 4th Edition 23 Reusing Function Names (Overloading) (cont'd.)
  • 24. ∗ Function call: cdabs(10); ∗ Causes compiler to use the function named cdabs() that expects and integer argument ∗ Function call: cdabs(6.28f); ∗ Causes compiler to use the function named cdabs() that expects a double-precision argument ∗ Major use of overloaded functions ∗ Constructor functions A First Book of C++ 4th Edition 24 Reusing Function Names (Overloading) (cont'd.)