SlideShare a Scribd company logo
1 of 34
A First Book of C++A First Book of C++
Chapter 6Chapter 6
Modularity Using FunctionsModularity Using Functions
(Pt. 2)(Pt. 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
∗ Most high-level languages require each function to be
coded separately
∗ Can lead to a profusion of names
∗ Example: functions to find the absolute value
∗ Three separate functions and prototypes required
void abs (int);
void fabs (float);
void dabs (double);
∗ Each function performs the same operation
∗ Only difference is data type handled
A First Book of C++ 4th Edition 3
Function Templates
∗ Example of function template:
template <class T>
void showabs(T number)
{
if (number < 0)
number = -number;
cout << "The absolute value of the number "
<< " is " << number << endl;
return;
}
∗ Template allows for one function instead of three
∗ T represents a general data type
∗ T replaced by an actual data type when compiler encounters a
function call
A First Book of C++ 4th Edition 4
Function Templates (cont'd.)
∗ Example (cont'd.):
int main()
{
int num1 = -4;
float num2 = -4.23F;
double num3 = -4.23456;
showabs(num1);
showabs(num2);
showabs(num3);
return 0;
}
∗ Output from above program:
The absolute value of the number is 4
The absolute value of the number is 4.23
The absolute value of the number is 4.23456
A First Book of C++ 4th Edition 5
Function Templates (cont'd.)
Calling function
Called
function
Pass by value arguments
∗ Passing data to a function:
∗ Called function receives only a copy of data sent to it
∗ Protects against unintended change
∗ Passed arguments called pass by value arguments
∗ A function can receive many values (arguments) from
the calling function
A First Book of C++ 4th Edition 6
Returning a Single Value
∗ Returning data from a function
∗ Only one value directly returned from function
∗ Called function header indicates type of data returned
∗ Examples:
void findMax(int x, int y)
∗ findMax accepts two integer parameters and returns no value
float findMax (float x, float y)
∗ findMax accepts two floating-point values and returns a
floating-point value
∗ To return a value, a function must use a return
statement
A First Book of C++ 4th Edition 7
Returning a Single Value (cont'd.)
x and y are of type integers
8
Returning a Single Value (cont'd.)
//Program 6.4
#include <iostream>
using namespace std;
int findMax(int, int); // function prototype
int main()
{
int firstnum, secnum, max ;
cout << “nEnter a number: ”;
cin >> firstnum;
cout << “Great! Please enter a second number: ”;
cin >> secnum;
max = findMax(firstnum, secnum); //var to store function’s result
cout << “nThe maximum of the two numbers is ” << max <<endl;
return 0;
}
9
Returning a Single Value (cont'd.)
//Program 6.4 (cont’d…)
int findMax(int x, int y) // function header
{
int maxnum;
if (x >= y)
maxnum = x;
else
maxnum = y;
// returning a single value, no cout, result printed in main()
return maxnum;
}
∗ Calling functions associate some overhead (excessive
usage of memory)
∗ Placing arguments in reserved memory (stack)
∗ Passing control to the function
∗ Providing stack space for any returned value
∗ Returning to correct point in calling program
∗ Overhead is justified when function is called many times
∗ Better than repeating code
A First Book of C++ 4th Edition 10
Inline Functions
∗ Overhead is not justified for small functions that are
not called frequently
∗ Still convenient to group repeating lines of code into a
common function name
∗ Inline function: avoids overhead problems
∗ C++ compiler instructed to place a copy of inline
function code into the program wherever the function is
called
A First Book of C++ 4th Edition 11
Inline Functions (cont'd.)
A First Book of C++ 4th Edition 12
∗ Returning a value from a function template is
identical to returning a value from a function
∗ Data type T is also used to declare the return type of
the function
A First Book of C++ 4th Edition 13
Templates with a Return Value
A First Book of C++ 4th Edition 14
template & function
declared before main ( )
∗ Called function usually receives values as pass by value
∗ A distinct advantage of C++
∗ Sometimes desirable to allow function to have direct access
to variables
∗ Address of variable must be passed to function
∗ Function can directly access and change the value stored there
∗ Pass by reference: passing addresses of variables received
from calling function
A First Book of C++ 4th Edition 15
Returning Multiple Values
∗ Reference parameter: receives the address of an
argument passed to called function
∗ Example: accept two addresses in function
newval()
∗ Function header:
void newval (double& num1, double& num2)
∗ Ampersand, &, means “the address of”
∗ Function prototype:
void newval (double&, double&);
A First Book of C++ 4th Edition 16
Passing and Using Reference
Parameters
∗ Scope: section of program where identifier is valid (known
or visible)
∗ Local variables (local scope): variables created inside a
function
∗ Meaningful only when used in expressions inside the function
in which it was declared
∗ Global variables (global scope): variables created outside
any function
∗ Can be used by all functions placed after the global variable
declaration
A First Book of C++ 4th Edition 17
Variable Scope
∗ Local variable with the same name as a global variable
∗ All references to variable name within scope of local variable
refer to the local variable
∗ Local variable name takes precedence over global variable
name
∗ Scope resolution operator (::)
∗ When used before a variable name, the compiler is
instructed to use the global variable
::number // scope resolution operator
// causes global variable to be used
A First Book of C++ 4th Edition 18
Scope Resolution Operator
∗ Avoid overuse of globals
∗ Too many globals eliminates safeguards provided by C++
to make functions independent
∗ Misuse does not apply to function prototypes
∗ Prototypes are typically global
∗ Difficult to track down errors in a large program using
globals
∗ Global variable can be accessed and changed by any
function following the global declaration
A First Book of C++ 4th Edition 19
Misuse of Globals
∗ Scope has a space and a time dimension
∗ Time dimension (lifetime): length of time that storage
locations are reserved for a variable
∗ All variable storage locations released back to operating
system when program finishes its run
∗ During program execution, interim(temporary) storage
locations are reserved
∗ Storage category: determines length of time that variable’s
storage locations are reserved
∗ Four classes: auto, static, extern, register
A First Book of C++ 4th Edition 20
Variable Storage Category
∗ Local variable can only be members of auto,
static, or register class
∗ auto class: default, if no class description included in
variable’s declaration statement
∗ Storage for auto local variables automatically
reserved (created)
∗ Each time a function declaring auto variables is called
∗ Local auto variables are “alive” until function returns
control to calling function
A First Book of C++ 4th Edition 21
Local Variable Storage Categories
∗ static storage class: allows a function to remember
local variable values between calls
∗ static local variable lifetime = lifetime of program
∗ Value stored in variable when function is finished is
available to function next time it is called
∗ Initialization of static variables (local and global)
∗ Done one time only, when program first compiled
∗ Only constants or constant expressions allowed
A First Book of C++ 4th Edition 22
Local Variable Storage Categories
(cont'd.)
A First Book of C++ 4th Edition 23
Local Variable Storage Categories
(cont'd.)
∗ register storage class: same as auto class except
for location of storage for class variables
∗ Uses high-speed registers
∗ Can be accessed faster than normal memory areas
∗ Improves program execution time
∗ Some computers do not support register class
∗ Variables automatically switched to auto class
A First Book of C++ 4th Edition 24
Local Variable Storage Categories
(cont'd.)
∗ Global variables: created by definition statements
external to a function
∗ Do not come and go with the calling of a function
∗ Once created, a global variable is alive until the program
in which it is declared finishes executing
∗ May be declared as members of static or extern
classes
∗ Purpose: to extend the scope of a global variable
beyond its normal boundaries
A First Book of C++ 4th Edition 25
Global Variable Storage Classes
∗ Passing incorrect data types between functions
∗ Values passed must correspond to data types declared
for function parameters
∗ Declaring same variable name in calling and called
functions
∗ A change to one local variable does not change value in
the other
∗ Assigning same name to a local and a global variable
∗ Use of a variable’s name only affects local variable’s
contents unless the :: operator is used
A First Book of C++ 4th Edition 26
Common Programming Errors
∗ Omitting a called function’s prototype
∗ The calling function must be alerted to the type of value
that will be returned
∗ Terminating a function’s header line with a semicolon
∗ Forgetting to include the data type of a function’s
parameters within the function header line
A First Book of C++ 4th Edition 27
Common Programming Errors
(cont'd.)
∗ A function is called by giving its name and passing data to it
∗ If a variable is an argument in a call, the called function
receives a copy of the variable’s value
∗ Common form of a user-written function:
returnDataType functionName(parameter list)
{
declarations and other C++ statements;
return expression;
}
A First Book of C++ 4th Edition 28
Summary
∗ A function’s return type is the data type of the value
returned by the function
∗ If no type is declared, the function is assumed to return
an integer value
∗ If the function does not return a value, it should be
declared as a void type
∗ Functions can directly return at most a single data
type value to their calling functions
∗ This value is the value of the expression in the return
statement
A First Book of C++ 4th Edition 29
Summary (cont'd.)
∗ Reference parameter: passes the address of a
variable to a function
∗ Function prototype: function declaration
∗ Scope: determines where in a program the variable
can be used
∗ Variable storage category: determines how long the
value in a variable will be retained
A First Book of C++ 4th Edition 30
Summary (cont'd.)
∗ Random numbers
∗ Series of numbers whose order can’t be predicted
∗ In practice, finding truly random numbers is hard
∗ Pseudorandom numbers
∗ Random enough for the type of applications being
programmed
∗ All C++ compilers provide two general-purpose
functions for generating random numbers
∗ rand() and srand()
A First Book of C++ 4th Edition 31
Chapter Supplement: Generating
Random Numbers
∗ Scaling
∗ Procedure for adjusting the random numbers produced by a
random-number generator to fall in a specified range
∗ Scaling random numbers to lie in the range 0.0 to 1.0
double(rand())/RAND_MAX)
∗ Scaling a random number as an integer value between 0
and N
rand() % (N+1)
int(double(rand())/RAND_MAX * N)
A First Book of C++ 4th Edition 32
Scaling
∗ Scaling
∗ Procedure for adjusting the random numbers produced by a
random-number generator to fall in a specified range
∗ Scaling random numbers to lie in the range 0.0 to 1.0
double(rand())/RAND_MAX)
∗ Scaling a random number as an integer value between 0
and N
rand() % (N+1)
int(double(rand())/RAND_MAX * N)
A First Book of C++ 4th Edition 33
Scaling
Write and test a function named milesToKm() that display
a table of miles converted to kilometers. The arguments
to the function should be the starting value of miles,
the stopping values of miles and the increment between
the mile values entered by the user. A call to
milesToKm(3,4,2) in your main() function should produce a
table of 4 lines with the starting value of 3(miles) and
in the increment of 2. The output should be a table of
miles and their equivalent kilometers values. Use the
relationship 1 mile = 1.61 km. Example output:
Miles Kilometer
3 4.83
5 8.05
7 11.27
9 14.49
A First Book of C++ 4th Edition 34
Exercise on Functions

More Related Content

What's hot (19)

C++ ch2
C++ ch2C++ ch2
C++ ch2
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
C++ Ch3
C++ Ch3C++ Ch3
C++ Ch3
 
C++11
C++11C++11
C++11
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
stack
stackstack
stack
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
Control Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, StructuresControl Statements, Array, Pointer, Structures
Control Statements, Array, Pointer, Structures
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
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
Infix to postfixInfix to postfix
Infix to postfix
 
Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 

Viewers also liked

Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functionsankita44
 
Random number generation (in C++) – past, present and potential future
Random number generation (in C++) – past, present and potential future Random number generation (in C++) – past, present and potential future
Random number generation (in C++) – past, present and potential future Pattabi Raman
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Slideshare Powerpoint presentation
Slideshare Powerpoint presentationSlideshare Powerpoint presentation
Slideshare Powerpoint presentationelliehood
 
State of the Word 2011
State of the Word 2011State of the Word 2011
State of the Word 2011photomatt
 

Viewers also liked (7)

Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functions
 
Random number generation (in C++) – past, present and potential future
Random number generation (in C++) – past, present and potential future Random number generation (in C++) – past, present and potential future
Random number generation (in C++) – past, present and potential future
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
functions of C++
functions of C++functions of C++
functions of C++
 
Slideshare Powerpoint presentation
Slideshare Powerpoint presentationSlideshare Powerpoint presentation
Slideshare Powerpoint presentation
 
State of the Word 2011
State of the Word 2011State of the Word 2011
State of the Word 2011
 

Similar to Csc1100 lecture06 ch06_pt2

Similar to Csc1100 lecture06 ch06_pt2 (20)

1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
What is storage class
What is storage classWhat is storage class
What is storage class
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Functions in c
Functions in cFunctions in c
Functions in c
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
Cpp
CppCpp
Cpp
 

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
 

Csc1100 lecture06 ch06_pt2

  • 1. A First Book of C++A First Book of C++ Chapter 6Chapter 6 Modularity Using FunctionsModularity Using Functions (Pt. 2)(Pt. 2)
  • 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. ∗ Most high-level languages require each function to be coded separately ∗ Can lead to a profusion of names ∗ Example: functions to find the absolute value ∗ Three separate functions and prototypes required void abs (int); void fabs (float); void dabs (double); ∗ Each function performs the same operation ∗ Only difference is data type handled A First Book of C++ 4th Edition 3 Function Templates
  • 4. ∗ Example of function template: template <class T> void showabs(T number) { if (number < 0) number = -number; cout << "The absolute value of the number " << " is " << number << endl; return; } ∗ Template allows for one function instead of three ∗ T represents a general data type ∗ T replaced by an actual data type when compiler encounters a function call A First Book of C++ 4th Edition 4 Function Templates (cont'd.)
  • 5. ∗ Example (cont'd.): int main() { int num1 = -4; float num2 = -4.23F; double num3 = -4.23456; showabs(num1); showabs(num2); showabs(num3); return 0; } ∗ Output from above program: The absolute value of the number is 4 The absolute value of the number is 4.23 The absolute value of the number is 4.23456 A First Book of C++ 4th Edition 5 Function Templates (cont'd.) Calling function Called function Pass by value arguments
  • 6. ∗ Passing data to a function: ∗ Called function receives only a copy of data sent to it ∗ Protects against unintended change ∗ Passed arguments called pass by value arguments ∗ A function can receive many values (arguments) from the calling function A First Book of C++ 4th Edition 6 Returning a Single Value
  • 7. ∗ Returning data from a function ∗ Only one value directly returned from function ∗ Called function header indicates type of data returned ∗ Examples: void findMax(int x, int y) ∗ findMax accepts two integer parameters and returns no value float findMax (float x, float y) ∗ findMax accepts two floating-point values and returns a floating-point value ∗ To return a value, a function must use a return statement A First Book of C++ 4th Edition 7 Returning a Single Value (cont'd.) x and y are of type integers
  • 8. 8 Returning a Single Value (cont'd.) //Program 6.4 #include <iostream> using namespace std; int findMax(int, int); // function prototype int main() { int firstnum, secnum, max ; cout << “nEnter a number: ”; cin >> firstnum; cout << “Great! Please enter a second number: ”; cin >> secnum; max = findMax(firstnum, secnum); //var to store function’s result cout << “nThe maximum of the two numbers is ” << max <<endl; return 0; }
  • 9. 9 Returning a Single Value (cont'd.) //Program 6.4 (cont’d…) int findMax(int x, int y) // function header { int maxnum; if (x >= y) maxnum = x; else maxnum = y; // returning a single value, no cout, result printed in main() return maxnum; }
  • 10. ∗ Calling functions associate some overhead (excessive usage of memory) ∗ Placing arguments in reserved memory (stack) ∗ Passing control to the function ∗ Providing stack space for any returned value ∗ Returning to correct point in calling program ∗ Overhead is justified when function is called many times ∗ Better than repeating code A First Book of C++ 4th Edition 10 Inline Functions
  • 11. ∗ Overhead is not justified for small functions that are not called frequently ∗ Still convenient to group repeating lines of code into a common function name ∗ Inline function: avoids overhead problems ∗ C++ compiler instructed to place a copy of inline function code into the program wherever the function is called A First Book of C++ 4th Edition 11 Inline Functions (cont'd.)
  • 12. A First Book of C++ 4th Edition 12
  • 13. ∗ Returning a value from a function template is identical to returning a value from a function ∗ Data type T is also used to declare the return type of the function A First Book of C++ 4th Edition 13 Templates with a Return Value
  • 14. A First Book of C++ 4th Edition 14 template & function declared before main ( )
  • 15. ∗ Called function usually receives values as pass by value ∗ A distinct advantage of C++ ∗ Sometimes desirable to allow function to have direct access to variables ∗ Address of variable must be passed to function ∗ Function can directly access and change the value stored there ∗ Pass by reference: passing addresses of variables received from calling function A First Book of C++ 4th Edition 15 Returning Multiple Values
  • 16. ∗ Reference parameter: receives the address of an argument passed to called function ∗ Example: accept two addresses in function newval() ∗ Function header: void newval (double& num1, double& num2) ∗ Ampersand, &, means “the address of” ∗ Function prototype: void newval (double&, double&); A First Book of C++ 4th Edition 16 Passing and Using Reference Parameters
  • 17. ∗ Scope: section of program where identifier is valid (known or visible) ∗ Local variables (local scope): variables created inside a function ∗ Meaningful only when used in expressions inside the function in which it was declared ∗ Global variables (global scope): variables created outside any function ∗ Can be used by all functions placed after the global variable declaration A First Book of C++ 4th Edition 17 Variable Scope
  • 18. ∗ Local variable with the same name as a global variable ∗ All references to variable name within scope of local variable refer to the local variable ∗ Local variable name takes precedence over global variable name ∗ Scope resolution operator (::) ∗ When used before a variable name, the compiler is instructed to use the global variable ::number // scope resolution operator // causes global variable to be used A First Book of C++ 4th Edition 18 Scope Resolution Operator
  • 19. ∗ Avoid overuse of globals ∗ Too many globals eliminates safeguards provided by C++ to make functions independent ∗ Misuse does not apply to function prototypes ∗ Prototypes are typically global ∗ Difficult to track down errors in a large program using globals ∗ Global variable can be accessed and changed by any function following the global declaration A First Book of C++ 4th Edition 19 Misuse of Globals
  • 20. ∗ Scope has a space and a time dimension ∗ Time dimension (lifetime): length of time that storage locations are reserved for a variable ∗ All variable storage locations released back to operating system when program finishes its run ∗ During program execution, interim(temporary) storage locations are reserved ∗ Storage category: determines length of time that variable’s storage locations are reserved ∗ Four classes: auto, static, extern, register A First Book of C++ 4th Edition 20 Variable Storage Category
  • 21. ∗ Local variable can only be members of auto, static, or register class ∗ auto class: default, if no class description included in variable’s declaration statement ∗ Storage for auto local variables automatically reserved (created) ∗ Each time a function declaring auto variables is called ∗ Local auto variables are “alive” until function returns control to calling function A First Book of C++ 4th Edition 21 Local Variable Storage Categories
  • 22. ∗ static storage class: allows a function to remember local variable values between calls ∗ static local variable lifetime = lifetime of program ∗ Value stored in variable when function is finished is available to function next time it is called ∗ Initialization of static variables (local and global) ∗ Done one time only, when program first compiled ∗ Only constants or constant expressions allowed A First Book of C++ 4th Edition 22 Local Variable Storage Categories (cont'd.)
  • 23. A First Book of C++ 4th Edition 23 Local Variable Storage Categories (cont'd.)
  • 24. ∗ register storage class: same as auto class except for location of storage for class variables ∗ Uses high-speed registers ∗ Can be accessed faster than normal memory areas ∗ Improves program execution time ∗ Some computers do not support register class ∗ Variables automatically switched to auto class A First Book of C++ 4th Edition 24 Local Variable Storage Categories (cont'd.)
  • 25. ∗ Global variables: created by definition statements external to a function ∗ Do not come and go with the calling of a function ∗ Once created, a global variable is alive until the program in which it is declared finishes executing ∗ May be declared as members of static or extern classes ∗ Purpose: to extend the scope of a global variable beyond its normal boundaries A First Book of C++ 4th Edition 25 Global Variable Storage Classes
  • 26. ∗ Passing incorrect data types between functions ∗ Values passed must correspond to data types declared for function parameters ∗ Declaring same variable name in calling and called functions ∗ A change to one local variable does not change value in the other ∗ Assigning same name to a local and a global variable ∗ Use of a variable’s name only affects local variable’s contents unless the :: operator is used A First Book of C++ 4th Edition 26 Common Programming Errors
  • 27. ∗ Omitting a called function’s prototype ∗ The calling function must be alerted to the type of value that will be returned ∗ Terminating a function’s header line with a semicolon ∗ Forgetting to include the data type of a function’s parameters within the function header line A First Book of C++ 4th Edition 27 Common Programming Errors (cont'd.)
  • 28. ∗ A function is called by giving its name and passing data to it ∗ If a variable is an argument in a call, the called function receives a copy of the variable’s value ∗ Common form of a user-written function: returnDataType functionName(parameter list) { declarations and other C++ statements; return expression; } A First Book of C++ 4th Edition 28 Summary
  • 29. ∗ A function’s return type is the data type of the value returned by the function ∗ If no type is declared, the function is assumed to return an integer value ∗ If the function does not return a value, it should be declared as a void type ∗ Functions can directly return at most a single data type value to their calling functions ∗ This value is the value of the expression in the return statement A First Book of C++ 4th Edition 29 Summary (cont'd.)
  • 30. ∗ Reference parameter: passes the address of a variable to a function ∗ Function prototype: function declaration ∗ Scope: determines where in a program the variable can be used ∗ Variable storage category: determines how long the value in a variable will be retained A First Book of C++ 4th Edition 30 Summary (cont'd.)
  • 31. ∗ Random numbers ∗ Series of numbers whose order can’t be predicted ∗ In practice, finding truly random numbers is hard ∗ Pseudorandom numbers ∗ Random enough for the type of applications being programmed ∗ All C++ compilers provide two general-purpose functions for generating random numbers ∗ rand() and srand() A First Book of C++ 4th Edition 31 Chapter Supplement: Generating Random Numbers
  • 32. ∗ Scaling ∗ Procedure for adjusting the random numbers produced by a random-number generator to fall in a specified range ∗ Scaling random numbers to lie in the range 0.0 to 1.0 double(rand())/RAND_MAX) ∗ Scaling a random number as an integer value between 0 and N rand() % (N+1) int(double(rand())/RAND_MAX * N) A First Book of C++ 4th Edition 32 Scaling
  • 33. ∗ Scaling ∗ Procedure for adjusting the random numbers produced by a random-number generator to fall in a specified range ∗ Scaling random numbers to lie in the range 0.0 to 1.0 double(rand())/RAND_MAX) ∗ Scaling a random number as an integer value between 0 and N rand() % (N+1) int(double(rand())/RAND_MAX * N) A First Book of C++ 4th Edition 33 Scaling
  • 34. Write and test a function named milesToKm() that display a table of miles converted to kilometers. The arguments to the function should be the starting value of miles, the stopping values of miles and the increment between the mile values entered by the user. A call to milesToKm(3,4,2) in your main() function should produce a table of 4 lines with the starting value of 3(miles) and in the increment of 2. The output should be a table of miles and their equivalent kilometers values. Use the relationship 1 mile = 1.61 km. Example output: Miles Kilometer 3 4.83 5 8.05 7 11.27 9 14.49 A First Book of C++ 4th Edition 34 Exercise on Functions