slide 1 chapter 3 function basics written by walter savitch, ucsd modified by tsung lee, nsysu ee
TRANSCRIPT
![Page 1: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/1.jpg)
Slide 1
Chapter 3
Function Basics
Written by Walter Savitch, UCSD
Modified by Tsung Lee, NSYSU EE
![Page 2: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/2.jpg)
Slide 2
Outline Introduction
Predefined Functions Those that return a value and those that don’t
Programmer-defined Functions Defining, declaring, calling functions
Scope Rules Local variables Global constants and global variables Blocks, nested scopes
![Page 3: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/3.jpg)
可再使用 (reuse) 一個觀念 形成此可再使用 (reuse) 的觀念
將此觀念放到一個模組 (module) 裏 此模組稱之為副程式 (subprogram) 在 C 與 C++ 裏,稱其為函數 (function)
在需要使用此觀念的程式位置 給定其名稱,引用(呼叫 (call) )
此形成單位的觀念
Slide 3
concept A
type A( )
{
}
concept A
…
A( ); // 引用 function A
…
![Page 4: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/4.jpg)
Slide 4
Introduction to Functions Functions (函數 ) are building blocks of programs
Extract meaningful subparts into functions : modular programming Can be invoked (called 呼叫 ) one to many times Also called
procedures(程序 ), subprograms(副程式 ), methods(方法 )
Typical subpart : Input – Process – Output (I-P-O) Use functions for these ‘pieces’
Can group other subparts into functions
Start
call B
A
Input
Processing
Output
End
C
Start
A
Input
Processing
Output
C
Start(B)
End(B)
B
function B
Input
Processing
Output
D
call B
End
D
B
* Input from outside* Prepare data for use
* Output to outside* Collect data for use
Modular programming
![Page 5: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/5.jpg)
C++ function (subprogram) Divide-and-conquer (分割征服策略) a program design
Divide a problem into a number of subproblems Divide the solving of a problem into the solving of subprograms Program solutions of the subproblems into subprograms Integrate these subprograms into a program (that can invoke the
subprograms)
Slide 5
A B
C D
P
Problem decomposition
A B
C D
P
Solving methods Caller (sub)program
… A( ) …
…B( ) … C( ) …
…
… D( ) …
A
B
C
D
P
Subprograms
![Page 6: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/6.jpg)
C++ function (subprogram) C++ functions (函數 ) are subprograms (副程式 )
A C++ function has a function body of processing flow (its task) It can be called (invoked) by a caller program
Call and pass parameters to the C++ function The C++ function executes its function body Then, return result(s) to the caller
Slide 6
Caller (sub)program
… A(a, b) …
…
…
…
int A(int x, int y)
{
…
…
return z;
}
P
Subprogram Acall A
a, b are passed to x, y
return from A
z is passed back
execution
![Page 7: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/7.jpg)
Functions (subprograms) can be formed with divide-and-conquer (切割征服)
Divide a problem into subproblems The program of a problem can be composed of functions (subprograms)
of
these subproblems
Slide 7
#include <iostream>using namespace std;
int main( ){ int numberOfLanguages;
cout << "Hello reader.\n" << “Welcome to C++.\n”;
cout << "How many programming languages have you used? ";
cin >> numberOfLanguages;
if (numberOfLanguages < 1) cout << "Read the preface. You may prefer\n" << "a more elementary book by the same author.\n"; else cout << "Enjoy the book.\n";
return 0;}
greeting
get number of languages
give advice
![Page 8: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/8.jpg)
Divide-and-conquer and subprograms
Simpler program Easy-to-design Easy-to-read Can be reused
Can be prepared in prior
Slide 8
#include <iostream>using namespace std;
int main( ){ int numberOfLanguages;
greeting( );
numberOfLanguages = get_languages( );
give_advice(numberOfLanguages);
return 0;}
void greeting( ){ cout << "Hello reader.\n" << “Welcome to C++.\n”;
}
int get_languages( )
{ int n; cout << "How many programming languages have you used?
"; cin >> n;
return n;}void give_advice(int n){ if (n < 1) cout << "Read the preface. You may prefer\n" << "a more elementary book by the same
author.\n"; else cout << "Enjoy the book.\n";}
call
call
call
![Page 9: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/9.jpg)
Slide 9
Predefined Functions Libraries (程式庫 ) : full of functions! Must ‘#include’ appropriate library
e.g.:<cmath>, <cstdlib> (Original ‘C’ libraries), <iostream> (cout, cin) Actually include header files (標頭檔 ) : cmath.h, cstdlib.h, iostream.h
![Page 10: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/10.jpg)
Slide 10
Predefined Functions Functions of two types
Those that return a value of some data type Performs a calculation,
and sends an ‘answer’ Receive k arguments
Those that do not void Performs an action,
but sends no ‘answer’ Receive k arguments
// This call terminates program
// and returns error code 1
![Page 11: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/11.jpg)
Slide 11
Using Predefined Functions Math functions very plentiful
Found in library <cmath.h> Most return a value (the ‘answer’)
Example: theRoot = sqrt(9.0);
sqrt : name of library function9.0 : argument (參數 ) or ‘starting input’ for functiontheRoot : variable used to assign ‘answer’ to
In I-P-O: I = 9.0 P = ‘compute the square root’ O = 3.0, which is the returned value (回覆值 )
& is assigned to theRoot
Input
Calculate
sqrt
Output
Start(sqrt)
End(sqrt)
function sqrt
![Page 12: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/12.jpg)
Slide 12
The Function Call Back to this assignment:
theRoot = sqrt(9.0); The expression ‘sqrt(9.0)’ is known as a function call(函數呼叫 ), or function
invocation
The argument in a function call (9.0) can be: A literal, a variable, or an expression
The call itself can be part of an expression:
bonus = sqrt(sales)/10;
A function call is allowed wherever it’s legal to usean expression of the function’s return type
![Page 13: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/13.jpg)
Copyright © 2002 Pearson Education, Inc. Slide 13
A Larger Example
2.381.54
![Page 14: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/14.jpg)
Slide 14
More Predefined Functions #include <cstdlib>
Library contains functions like: abs() // Returns absolute value of an int labs() // Returns absolute value of a long int fabs() // Returns absolute value of a float
fabs() is actually in library <cmath> Remember: libraries were added after C++ was
‘born’, in incremental phases Refer to appendices/manuals for details
![Page 15: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/15.jpg)
Slide 15
More Math Functions pow(x, y)
Returns x to the power y : xy
double result, x = 3.0, y = 2.0;result = pow(x, y); // 3.02.0
cout << result;
Here 9.0 is displayed since 3.02.0 = 9.0 Notice this function receives two
arguments
A function can have any number ofarguments, of varying data types
![Page 16: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/16.jpg)
Slide 16
Random Number Generator Return ‘randomly chosen’ number
Used for simulations and games
Usage Predefined function rand()
int rand() Takes no arguments Returns value between 0 & RAND_MAX
Scalingrand() % 6
Squeezes random number into smaller range (between 0 & 5) Shifting
rand() % 6 + 1 // Shifts range between 1 & 6 (e.g.: die roll)
rand() % 10 + 10 // Random int between 10 & 20 Produce a random double between 0.0 & 1.0
rand() / static_cast<double>(RAND_MAX) Type cast used to force double-precision division
![Page 17: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/17.jpg)
Slide 17
Random Number Seed Pseudorandom numbers
Calls to rand() produce given ‘sequence’ of random numbers
Use ‘seed’ to alter sequence, or set up a pseudo random sequence
srand(seed_value); void function Receives one argument, the ‘seed’ Can use any seed value, including system time:
srand(time(0)); time() returns system time as numeric value
Seconds since Jan. 1, 1970 Library <time> contains time() functions
Generates a sequence of 10 random numbers
Generates the same random number sequence
![Page 18: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/18.jpg)
Copyright © 2002 Pearson Education, Inc. Slide 18
Random Function Example
![Page 19: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/19.jpg)
Slide 19
Sample Dialogue
![Page 20: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/20.jpg)
Slide 20
Outline Introduction
Predefined Functions Those that return a value and those that don’t
Programmer-defined Functions Defining, declaring, calling functions
Scope Rules Local variables Global constants and global variables Blocks, nested scopes
![Page 21: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/21.jpg)
Slide 21
Programmer-Defined Functions Write your own functions!
Build (extract) meaningful blocks into functions Divide & Conquer Readability Re-use
Your function ‘definition’ can store in Same file as main() Separate file so others can use it, too
![Page 22: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/22.jpg)
Slide 22
Function Use Need 3 Pieces to use functions
Function declaration (function prototype) : declare it<return_type> FnName(<formal-parameter-list>);
Information for compiler Placed before any calls (usually in the beginning) to properly
interpret calls E.g. int max(int x, int y);
Function definition : define it <return_type> FnName(<formal-parameter-list>){
function_body_statements}
Actual implementation/code for what function does E.g. int max(int x, int y) { if (x > y) return x; else return y; }
Function call : use it in program… FnName(argument-list) …
Transfer control to function E.g. k = a + b * max(c, 20);
![Page 23: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/23.jpg)
Slide 23
Example of Function Use Function declaration
double totalCost(int numberParameter, double priceParameter);
Function definitiondouble totalCost(int numberParameter, double priceParameter){
const double TAXRATE = 0.05;double subTotal;subtotal = priceParameter * numberParameter;return (subtotal + subtotal * TAXRATE);
}
Function callbill = totalCost(number, price);
call arguments – actual parameters
replaced by the return value
formal parameters(參數 )
function body
return result
type of
returned value
![Page 24: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/24.jpg)
Slide 24
Function Declaration Compiler only needs to know:
Return type Function name Parameter list
Formal parameter names not needed:double totalCost(int, double);
Still ‘should’ put in formal parameter names Improves readability
![Page 25: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/25.jpg)
Slide 25
Function Definition Placed after function main()
NOT ‘inside’ function main()! No function is ever ‘part’ of another
Formal parameters in function definition Parameter variables are ‘Placeholders’ for data sent in
i.e. Argument values are copied to parameter variables
return statement Sends data back to caller
![Page 26: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/26.jpg)
Slide 26
Function Example
![Page 27: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/27.jpg)
Slide 27
Parameter vs. Argument Formal parameters or arguments
In function declaration In function definition’s header
Actual parameters or arguments In function call
Technically Parameter is ‘formal’ piece Argument is ‘actual’ piece*
![Page 28: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/28.jpg)
Slide 28
Boolean Return-Type Functions Return-type can be any valid type (here is bool)
Function declaration/prototype:bool appropriate(int rate);
Function’s definition:bool appropriate (int rate){
return ((rate>=10)&&(rate<20)) || (rate==0);}
Returns ‘true’ or ‘false’
Function call, from some other function:if (appropriate(entered_rate))
cout << “Rate is valid\n”;
![Page 29: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/29.jpg)
Slide 29
Void Functions Functions return no value
Function declaration / prototypevoid showResults (double fDegrees, double cDegrees);
Return type is void Function definition:
void showResults(double fDegrees, double cDegrees){
cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(1);cout << fDegrees
<< “ degrees fahrenheit equals \n”<< cDegrees << “ degrees celsius.\n”;
} No return statement Or with return statement with no return value
return;
![Page 30: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/30.jpg)
Slide 30
Void Functions Function call
showResults(degreesF, degreesC);
showResults(32.5, 0.3);
Notice no assignment, since no value returned
Actual arguments : (degreesF, degreesC) or (32.5, 0.3); Passed to function’s (fDegrees, cDegrees) Function is called to ‘do it’s job’ with the data passed in
![Page 31: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/31.jpg)
Slide 31
More on Return Statements Transfers control back to ‘calling’ function
For return type other than void MUST have return statement to return control with result
For void functions return; statement return control with no result Or return statement is optional
Closing } would implicitly return control from void function compiler insert return; statement there
![Page 32: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/32.jpg)
Copyright © 2002 Pearson Education, Inc. Slide 32
Function Example
![Page 33: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/33.jpg)
Slide 33
Functions Calling Functions We’re already doing this!
main() IS a function!
Common for functions to call many other functions
Function can even call itself ‘Recursion’
Only requirement Function’s declaration must appear first
![Page 34: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/34.jpg)
Slide 34
Preconditions and Postconditions Comment function declaration:
Precondition : conditions of input parameters Postcondition : conditions of output (returned) results
void showInterest(double balance, double rate);//Precondition: balance is nonnegative account balance// rate is interest rate as percentage//Postcondition: amount of interest on given balance,// at given rate …
As function specification Good for software engineering
Check for correctness Reused by self or other programmers
![Page 35: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/35.jpg)
Slide 35
main( ) Function main() IS a function
One and only one function called main()in a program
Who calls main()? Operating system Should return ‘int’ or ‘void’
int returned value as program exit code Value returned to ‘caller’ Here: operating system
![Page 36: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/36.jpg)
Slide 36
Outline Introduction
Predefined Functions Those that return a value and those that don’t
Programmer-defined Functions Defining, declaring, calling functions
Scope Rules Local variables Global constants and global variables Blocks, nested scopes
![Page 37: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/37.jpg)
Slide 37
Scope Rules Variable’s scope (範疇 ) : where it can be used
Global scope (全域範疇 ) Function scope (函數範疇 ) Block scope (區塊範疇 ) Nested scope (巢狀範疇 )
![Page 38: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/38.jpg)
Slide 38
Contour model of scopes Variable and parameter declarations
are organized in nested contours
Variable and parameter usages can
refer from its containing contour outward
The first contour contains the variable
with the same name is used
PImain( )area( )volume( )
cin, cout, …pow( ), …
radius
radius
radiusOfBothareaOfCirclevolumeOfSphere
Global scope
main( ) scope
area( ) scope
volume( ) scope
![Page 39: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/39.jpg)
Slide 39
Global Scope Declarations ‘outside’ any function body
Global to all functions in that file Can be used by any statements globally
Global declarations typical for constants: const double TAXRATE = 0.05; Declare globally so all functions have scope
Global variables? Possible, but SELDOM-USED Dangerous: no control over usage!
![Page 40: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/40.jpg)
Slide 40
Example of Global Scope
declarations in scopes
![Page 41: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/41.jpg)
Slide 41
Scope of exampleGlobal scope
main( ) scope
area( ) scope
volume( ) scope
PImain( )area( )volume( )
cin, cout, …pow( ), …
radius
radius
radiusOfBothareaOfCirclevolumeOfSphere
![Page 42: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/42.jpg)
Slide 42
Function Scope Local variables (區域變數 )
Declared inside body of given function Available only within that function
Can have variables with same namesdeclared in different functions
Scope is local: ‘that function is it’s scope’
Local variables are preferred Maintain individual control over data Need-to-know basis
Functions should declare whatever local data needed to ‘do their job’
![Page 43: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/43.jpg)
Copyright © 2002 Pearson Education, Inc. Slide 43
Example of Function Scope
declarations in scopes
![Page 44: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/44.jpg)
Slide 44
Scope of exampleGlobal scope
main( ) scope
estimateOfTotal( )
scope
main( )estimatOfTotal( )
cin, cout, …
minPeas, maxPeas, podCount
averagePea
minCount, maxCount, podCountaveragePea, yield
![Page 45: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/45.jpg)
Slide 45
Block Scope Declare data inside compound statement { … }
Called a ‘block’{ <declarations>
…
} The variables in <declarations> has ‘block-scope’
Those variables can only be used inside the block Note: all function definitions are blocks!
This provides local ‘function-scope’
Loop blocks:for (int ctr=0;ctr<10;ctr++){
sum+=ctr;}
Variable ctr has scope in loop body block only
![Page 46: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/46.jpg)
Slide 46
Nested Scope Variables defined in a block
can be used in the inner nested blocks
for (int i = 0; i < 100 ; i++)
{
for (int j = 0; j < 200 ; j++)
{
int k;
k = i + j;
cout << k << endl;
}
cout << i << endl;}
the outer block’s i variable
Outer block scope
Inner block scope
i
jk
![Page 47: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/47.jpg)
Slide 47
Scope of example
Outer block scope
Middle block scope
Inner block scope
x1
x3
x2
![Page 48: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/48.jpg)
Slide 48
Nested Scope Same name variables declared in multiple nested blocks
Very legal; scope is ‘block-scope’ No ambiguity
Each name is distinct within it’s scopefor (int i = 0; i < 100 ; i++){
for (int j = 0; j < 200 ; j++){
int i, k;cin >> i;k = i + j; // the inner icout << k << endl;
}cout << i << endl; // the outer i
}
Outer block scope
Inner block scope
i
jik
![Page 49: Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE](https://reader035.vdocuments.site/reader035/viewer/2022062321/56649f265503460f94c3d8ea/html5/thumbnails/49.jpg)
Slide 49
Procedural Abstraction Need to know ‘what’ function does, not
‘how’ it does it! Think ‘black box’
Implement functions like black box (Information Hiding)
Hide details of ‘how’ function does it’s job Not use global variables in functions Only use parameter variables and local variables
Users to use the function Only needs: declaration – above box or function prototype
type0 function_name(type1 par_var1, …);
Does NOT need function definition
Uses Implementers designs its details Users only need to know its interface
Func_name
Type1 par_var1
Type2 par_var2
Type0 result
Typek par_vark