Sei sulla pagina 1di 52

Functions

CSIS1117 Computer Programming

Contents

What is a function?
Predefined function provided by C++ library
Mechanism for function calls
User defined function
function prototype
Local variables
Scope of variables
Global variables

c1117 lecture 4

Function

A function is a small program which accomplishes


a specific task.
We can interact (give input and get output) with
functions in our programs for finishing some tasks
C++ libraries provide a lot of predefined functions
that we can use.

For example, sqrt(x) is a function in the cmath library


to compute the square root of x (x is a real number).

c1117 lecture 4

Passing input to
the function sqrt
int
int main(){
main(){
...
...
...
...
sqrt(x);
sqrt(x);
...
...
}}

Our program

double
double sqrt(){
sqrt(){
...
...
}}

In cmath library

Getting output from


the function sqrt

We dont need to write codes for finding the square root


of a number (actually it is difficult to do so), we can call
the function sqrt to help.
c1117 lecture 4

We can call (or invoke) a function using its name


with necessary input (arguments)

At most one value is returned by a function as the


output (return value).

The type of the arguments are specified for each


function

The type of the return value is specified for each


function

The function call sqrt(x) is an expression

We can place a function call in any places where an


expression is expected.

c1117 lecture 4

Function

We usually use the following notation to describe a


function: double sqrt(double x)
double sqrt(double x)

Data type for


the return value

Data type for


the argument

In calling a function, we need to consider:

The name of the function


Type of the return value
Number of arguments
Type of each argument

c1117 lecture 4

sqrt
double
1
double

//
// function
function call
call
double
double val
val == sqrt(9.0)
sqrt(9.0)

We need to specify the library, which contains the


code of the predefined functions, in our program.

e.g. #include <cmath> for using sqrt()

Example: Try to find the roots of a quadratic


equation, ax2+bx+c=0. You can assume that the
two roots exist.

The two roots can be calculated by the following


formula:
-b b2-4ac
roots =
2a

c1117 lecture 4

Example
We need to include the library in
#include
<iostream>
#include <iostream>
using the predefined function
#include
<cmath>
#include <cmath>

int
int main()
main() {{
Invoke the
double
double a,
a, b,
b, c;
c;
sqrt function
cin
cin >>
>> aa >>
>> bb >>
>> c;
c;
in cmath
double
double delta
delta == bb ** bb 44 ** aa ** c;
c;
double
double r1
r1 == (-b
(-b ++ sqrt(delta))
sqrt(delta)) // (2
(2 ** a);
a);
double
double r2
r2 == (-b
(-b -- sqrt(delta))
sqrt(delta)) // (2
(2 ** a);
a);
cout
cout <<
<< "the
"the roots
roots are:
are: "" <<
<< r1
r1
<<
<< ",
", "" <<
<< r2
r2 <<
<< endl;
endl;
}}
We can put the function calls in any places where
expressions are expected.

c1117 lecture 4

Flow of control

The execution of the statements in the main


function is from top to bottom.
The flow of control is passed from one statement
to the other.
In evaluating an expression involving function call,
the flow of control actually is suspended in that
statement.

The control is passed to the function (sub-program)


When the sub-program finishes, the control is passed
back to the original statement
The control is resumed from that calling statement.

c1117 lecture 4

Mechanism for function calls


#include
#include <cmath>
<cmath>
int
int main()
main() {{
//
//
cin
cin >>
>> aa >>
>> bb >>
>> c;
c;
delta
delta == bb ** bb 44 ** aa ** c;
c;
root1
root1 == (-b
(-b ++ sqrt(delta))/(2*a);
sqrt(delta))/(2*a);
root2
root2 == (-b
(-b -- sqrt(delta))/(2*a);
sqrt(delta))/(2*a);
cout
cout <<
<< "the
"the roots
roots are:
are: "" <<
<< r1
r1
<<
<< ",
", "" <<
<< r2
r2 <<
<< endl;
endl;
}}
11
11
-6
-6
c1117 lecture 4

Main memory
1

1
-6

b
c

25

delta
root1
root2

Command
prompt
10

Mechanism for function calls


#include
#include <cmath>
<cmath>
int
int main()
main() {{
//
//
cin
cin >>
>> aa >>
>> bb >>
>> c;
c;
delta
delta == bb ** bb 44 ** aa ** c;
c;
root1
root1 == (-b
(-b ++ sqrt(delta))/(2*a);
sqrt(delta))/(2*a);
root2
root2 == (-b
(-b -- sqrt(delta))/(2*a);
sqrt(delta))/(2*a);
cout<<
cout<< "the
"the roots
roots are:
are: "" <<
<< root1
root1
<<
<< ",
", "" <<
<< root2
root2 <<
<< endl;
endl;
delta
}}
main() is suspended, the
control and the delta are
passed to the sqrt function
c1117 lecture 4

Main memory
1

1
-6

b
c

25

delta
root1
root2

double
double sqrt(double
sqrt(double x){
x){
...}
...}
in cmath library
11

Mechanism for function calls


Main memory

#include
#include <cmath>
<cmath>
1
a
int
int main()
main() {{
//
1
//
b
cin
cin >>
>> aa >>
>> bb >>
>> c;
c;
c
-6
delta
=
b
*
b

4
*
a
*
c;
delta = b * b 4 * a * c;
delta
25
root1
root1 == (-b
(-b ++ sqrt(delta))/(2*a);
sqrt(delta))/(2*a);
root2
root2 == (-b
(-b -- sqrt(delta))/(2*a);
sqrt(delta))/(2*a);
2
root1
cout<<
cout<< "the
"the roots
roots are:
are: "" <<
<< root1
root1
root2
<<
<< ",
", "" <<
<< root2
root2 <<
<< endl;
endl;
}}
5
Once sqrt finished, the
double
double sqrt(double
sqrt(double x){
x){
control and the result are
...}
...}
passed back to the original
statement
in cmath library
c1117 lecture 4

12

Mechanism for function calls


Main memory

#include
#include <cmath>
<cmath>
1
a
int
int main()
main() {{
//
1
//
b
cin
cin >>
>> aa >>
>> bb >>
>> c;
c;
c
-6
delta
=
b
*
b

4
*
a
*
c;
delta = b * b 4 * a * c;
delta
25
root1
root1 == (-b
(-b ++ sqrt(delta))/(2*a);
sqrt(delta))/(2*a);
root2
root2 == (-b
(-b -- sqrt(delta))/(2*a);
sqrt(delta))/(2*a);
2
root1
cout<<
cout<< "the
"the roots
roots are:
are: "" <<
<< root1
root1
-3
root2
<<
<< ",
", "" <<
<< root2
root2 <<
<< endl;
endl;
delta
}}
5
main is suspended
double
double sqrt(double
sqrt(double x){
x){
nd
again for the 2 call of
...}
...}
sqrt
c1117 lecture 4

in cmath library
13

Mechanism for function calls


#include<cmath>
#include<cmath>
int
int main()
main() {{
//
//
cin
cin >>
>> aa >>
>> bb >>
>> c;
c;
delta
delta == bb ** bb 44 ** aa ** c;
c;
root1
root1 == (-b
(-b ++ sqrt(delta))/(2*a);
sqrt(delta))/(2*a);
root2
root2 == (-b
(-b -- sqrt(delta))/(2*a);
sqrt(delta))/(2*a);
cout<<
cout<< "the
"the roots
roots are:
are: "" <<
<< root1
root1
<<
<< ",
", "" <<
<< root2
root2 <<
<< endl;
endl;
}}
11
11
-6
-6
the roots are: 2, -3
c1117 lecture 4

Main memory
1

1
-6

b
c

25

delta

root1

-3

root2

Command
prompt

14

Some predefined functions


In library cmath -- #include<cmath>
Function

Description

double sqrt(double x)

square root of x

double pow(double x, double y) x to the power of y (ie. xy)


double fabs(double x)

absolute value of x

double ceil(double x)

ceiling, e.g. ceil(3.2)=4

double floor(double x)

floor, e.g. floor(3.2)=3

In library cstdlib -- #include<cstdlib>


int rand()

return a random integer

int abs (int x)

integer absolute value of x

c1117 lecture 4

15

Type casting

Sometimes, we need to convert a value from one


type to another:
int tol_candy, no_of_people;
cin >> tol_candy >> no_of_people;
cout << "The number of candies per person: "
<< tol_candy / no_of_people;

After evaluating the expression, force the type


of the value to the type some_type.
You dont need to include any library for using static_cast.

See casting.cc as an example

c1117 lecture 4

16

Expressions for arguments

Functions require zero, one, or more arguments.

e.g. rand takes no arguments, sqrt takes one and pow


takes two.

An argument can also be an expression. The


expression is evaluated before calling the function.
double
double w,
w, h;
h;
w*w + h*h is evaluated
before calling sqrt
cin
cin >>
>> ww >>
>> h;
h;
cout
cout <<
<< sqrt(w*w
sqrt(w*w ++ h*h)
h*h) <<
<< endl;
endl;

As function call is also an expression, it can be used


in the argument of another function
double
double root1
root1 =(-b
=(-b ++ sqrt(pow(b,2)-4*a*c))/(2*a);
sqrt(pow(b,2)-4*a*c))/(2*a);

c1117 lecture 4

17

User defined functions

The programs youve written so far consists of


only the main function. In fact, you can define
other functions to help organizing your program
Designing functions in programs is the most
important skill in programming.
Advantages of using functions:

Re-usability: Once we implemented a function, we can


invoke it many times in different parts of a program.
Readability: The program becomes more structural.

c1117 lecture 4

18

Example

Consider a problem: Given 3 coordinates (x1, y1),


(x2, y2) and (x3, y3), find the shortest distance
among the 3 pairs of coordinates.

One solution is to calculate the distances of 3 pairs of


coordinates and return the shortest one.
In doing so, we have to write the codes for finding the
distance between a pair of coordinates three times,
even though they are very similar.
Moreover, its easy to make mistake if code is
duplicated.
See closest.cc for an example.

c1117 lecture 4

19

Example
//finding
//finding the
the distance
distance between
between (x1,y1)&(x2,y2)
(x1,y1)&(x2,y2)
double
double dx12,
dx12, dy12,
dy12, dist12;
dist12;
dx12
dx12 == x1
x1 x2;
x2; dy12
dy12 == y1
y1 y2;
y2;
dist12
dist12 == sqrt(dx12
sqrt(dx12 ** dx12
dx12 ++ dy12
dy12 ** dy12);
dy12);
//finding
//finding the
the distance
distance between
between (x1,y1)&(x3,y3)
(x1,y1)&(x3,y3)
double
double dx13,
dx13, dy13,
dy13, dist13;
dist13;
dx13
dx13 == x1
x1 x3;
x3; dy13
dy13 == y1
y1 y3;
y3;
dist13
dist13 == sqrt(dx13
sqrt(dx13 ** dx13
dx13 ++ dy13
dy13 ** dy13);
dy13);
//finding
//finding the
the distance
distance between
between (x2,y2)&(x3,y3)
(x2,y2)&(x3,y3)
...
...

Codes are repeated and its easy to make mistakes.


c1117 lecture 4

20

Defining functions

The natural solution to avoid code duplication is to


define a function.

We can define a function to find the distance of any two


coordinates.
Imagine that if there were such a predefined function
that takes a pair of coordinates and returns the distance
between them, our code could be simplified as:

//finding the
//coordinates
double dist12
double dist23
double dist31
c1117 lecture 4

distances of the 3 pairs of


=
=
=

pair_distance(x1,
pair_distance(x2,
pair_distance(x3,

y1,
y2,
y3,

x2,
x3,
x1,

y2);
y3);
y1);
21

Our next task is to design the function


pair_distance.
A function can be considered as a smaller program
with input & output.

See closest-fun.cc for an example.


The arguments passed to the function is the input
The value/result computed by the function is the output

c1117 lecture 4

22

Structure of a function
return type

function
name

parameters of the function

double
double pair_distance(double
pair_distance(double x1,
x1, double
double y1,
y1,
double
double x2,
x2, double
double y2){
y2){
Body of
double
the
double dx
dx == x1
x1 -- x2;
x2;
double
function
double dy
dy == y2
y2 -- y2;
y2;
double
double distance
distance == sqrt(dx
sqrt(dx ** dx
dx ++ dy
dy ** dy);
dy);
return
return distance;
distance;
}}
Variables can be declared
inside the function.
return statement: return
the value to caller
c1117 lecture 4

23

A function heading consists of a return type, a


function name and a parameters list.

return type: specifying the type of value that the


function will send back to the caller, e.g. double.
function name: name of the function, e.g.
pair_distance
Parameter list: inputs to the function. The parameter
types and number of parameters should be specified.
e.g. pair_distance takes 4 parameters which are
used to store the arguments passed to it.

Each parameter has a type to denote the possible value


that can be stored.

c1117 lecture 4

24

A function is defined uniquely by its heading


(function prototype).
We can put any no. of statements and declare
variables inside the function body.
The value as well as the flow of control, are sent
back to the caller in the return statement

The execution of the function is terminated after


executing (any one of the) return statement.

c1117 lecture 4

25

Understanding function calls

In reading a program with function definitions, we


shall not assume the execution starts from the top
till the bottom of the program file.
In fact, the execution begins at the main function,
no matter how many function definitions are put
before it.
Therefore, to understand the computation of a
C++ program, we need to trace the execution in
main.

c1117 lecture 4

26

Mechanism for function calls

double
double pair_distance(double
pair_distance(double x1,
x1, double
double y1,
y1,
double
double x2,
x2, double
double y2){
y2){
//
//
}}
int
int main()
main() {{

double
double dist12
dist12 == pair_distance(
pair_distance( );
);
}}

Execution starts at the main function


c1117 lecture 4

27

Mechanism for function calls


double
double pair_distance(double
pair_distance(double x1,double
x1,double y1,
y1,
double
double x2,
x2, double
double y2){
y2){
double
double dx
dx == x1-x2;
x1-x2;
double
double dy
dy == y1-y2;
y1-y2;
double
double dist
dist == sqrt(dx*dx
sqrt(dx*dx ++ dy*dy);
dy*dy);
return
return dist;
dist;
}}
pair_distance(double
pair_distance(double px,
px, double
double py,
py,
qx,
qx, double
double qy)
qy)

double
double
double
double
{{ }}
int
int main()
main() {{

double
double dist12
dist12 == pair_distance(
pair_distance( );
);
}}

When executing to a function call, the control is


suspended and passed to the function code.

c1117 lecture 4

28

Mechanism for function calls


double
double pair_distance(double
pair_distance(double
x1,double
x1,double y1,
y1, double
double x2,
x2, double
double y2){
y2){
double
double dx
dx == x1-x2;
x1-x2;
double
double dy
dy == y1-y2;
y1-y2;
double
double dist
dist == sqrt(dx*dx
sqrt(dx*dx ++ dy*dy);
dy*dy);

return
dist;
return
dist;
//in
cmath
library
double
pair_distance(double
px,
//in
cmathpair_distance(double
library
double
px, double
double
}}
py,
qx,
double
sqrt(double
x){
py, double
double
qx, double
double
qy)
double
sqrt(double
x){ qy)
double
{{ }} val;
double
val;
int
int main()
main() {{

return
val;
return
val; }}
double
double dist12
dist12 == pair_distance(
pair_distance( );
);
}}

The control is suspended again and


passed to the predefined function, sqrt.

c1117 lecture 4

29

Mechanism for function calls


double
double pair_distance(double
pair_distance(double
x1,double
x1,double y1,
y1, double
double x2,
x2, double
double y2){
y2){
double
double dx
dx == x1-x2;
x1-x2;
double
double dy
dy == y1-y2;
y1-y2;
double
double dist
dist == sqrt(dx*dx
sqrt(dx*dx ++ dy*dy);
dy*dy);

return
dist;
return
dist;
//in
cmath
library
double
pair_distance(double
px,
//in
cmathpair_distance(double
library
double
px, double
double
}}
py,
qx,
double
sqrt(double
x){
py, double
double
qx, double
double
qy)
double
sqrt(double
x){ qy)
double
{{ }} val;
double
val;
int
int main()
main() {{

return
val;
return
val; }}
double
double dist12
dist12 == pair_distance(
pair_distance( );
);
}}
After the return statement of sqrt is executed, the

result is returned to the caller (pair_distance),


and the control is resumed.
c1117 lecture 4

30

Mechanism for function calls


double
double pair_distance(double
pair_distance(double
x1,double
x1,double y1,
y1, double
double x2,
x2, double
double y2){
y2){
double
double dx
dx == x1-x2;
x1-x2;
double
double dy
dy == y1-y2;
y1-y2;

double
double dist
dist == sqrt(dx*dx
sqrt(dx*dx ++ dy*dy);
dy*dy);
return
double
return dist;
dist; px,
double pair_distance(double
pair_distance(double
px, double
double
py,
}} double
py, double
double qx,
qx,
double qy)
qy)
{{ }}
int
int main()
main() {{

double
double dist12
dist12 == pair_distance(
pair_distance( );
);
}}
After the return statement of pair_distance is

executed, the result is again returned to the caller


(the main function), and the control is resumed.
c1117 lecture 4

31

Viewing execution

We can also picture the execution of a program


using a tree-like diagram.
main()

pair_distance
(4,0,1,3)

sqrt(18)

c1117 lecture 4

pair_distance
(1,3,3,5)

sqrt(8)

pair_distance
(3,5,4,0)

sqrt(26)

32

Function prototype

The order of the functions in a program matters.

The compiler performs the translation by reading the


program from top to bottom.
Errors will be given by compiler if the function is not
defined before it is called.

C++ required that either the complete function


definition or the function prototype appears in the
code before the function is called.

Function prototype: just like the function heading,


specifies the name, return type and the parameter list of
the function.
Function declaration should be ended with a semi-colon.

c1117 lecture 4

33

Function prototype

In writing the prototype, only the types in the parameter


list and the number of parameters are important. The name
of each parameter is optional.
Using prototypes, the function definitions can be placed in
arbitrary order.
Ends with a semi-colon
double
double pair_distance(double
pair_distance(double
x1,double
x1,double y1,
y1, double
double x2,
x2, double
double y2);
y2);
double
double pair_distance(double,
pair_distance(double, double,
double,
double,
double, double);
double);

c1117 lecture 4

34

Function prototype
#include
#include <iostream>
<iostream>

Defining the function


before main().

double
double pair_distance(double
pair_distance(double x1,
x1,
double
double y1,
y1, double
double x2,
x2, double
double y2)
y2)
{{ }}
int
int main()
main()
{{ }}
#include
#include <iostream>
<iostream>

Declare the
function first
by prototype.
Defining the function
after main().
c1117 lecture 4

double
double pair_distance(double
pair_distance(double x1,
x1,
double
double y1,
y1, double
double x2,
x2, double
double y2);
y2);
int
int main()
main()
{{ }}
double
double
double
double
{{ }}

pair_distance(double
pair_distance(double x1,
x1,
y1,
y1, double
double x2,
x2, double
double y2)
y2)

35

Dummy names

The names of the parameters are dummy. They


can always be renamed without affecting the
meaning of the function.
Yet, its better to give meaningful names to
parameters.

These two functions are


double
double pair_distance(double
pair_distance(double px,
px,
the same, but it is more
double
double py,
py, double
double qx,
qx, double
double qy)
qy) readable if meaningful
{{ }}
names are used.
double
double
double
double
{{ }}
c1117 lecture 4

pair_distance(double
pair_distance(double x1,
x1,
y1,
y1, double
double x2,
x2, double
double y2)
y2)

36

Boolean functions

Functions can return more than just number. In


fact, it can return bool, char, string, etc.
bool
bool isValidTriangle(
isValidTriangle( int
int a,
a, int
int b,
b, int
int c){
c){
if
if ((a+b
((a+b << c)
c) &&
&& (b+c
(b+c << a)
a) &&
&& (c+a
(c+a << b))
b))
return
true;
return true;
else
else
return
return false;
false;
}}
//
// aa simpler
simpler version
version
bool
bool isValidTriangle(
isValidTriangle( int
int a,
a, int
int b,
b, int
int c){
c){
return
return (a+b
(a+b << c)
c) &&
&& (b+c
(b+c << a)
a) &&
&& (c+a
(c+a << b);
b);
}}

Ex. Write a boolean function for checking if a year is


a leap year; e.g., bool is_leap(int year);
c1117 lecture 4

37

More examples
Suppose we want to write a program to determine
the grade of a student based on the assignment
scores and exam result.

The grading is based on the overall result.

A: 100-85, B: 84-75, C: 74-65, D: 64-50, F: 49-0

The overall result is composed of 50% from the course


work and 50% from the exam.
Coursework is the average of the 6 assignments.

See grade.cc

c1117 lecture 4

38

Procedural Abstraction

In the previous example, we introduce functions


that are used only once.

They dont serve the code repetition aspect.

The usage of function in this example is to


abstract the details of a computation.

Abstraction, in simple words, means to name a


sequence of operations.
The course work of different courses may be different.

Course XXXX counts only the best 5 assignments.


Course XXXX uses a weighted average of the
assignments.

c1117 lecture 4

39

The computation of the overall result is also put


into a separate function.

How about if the coursework-to-exam ratio is changed


to 40-60?

The main flow of the program does not change.


The changes are localized to the specific function.
Good for maintenance and debugging.

c1117 lecture 4

40

Void function

In some situations, we use functions just for


completing subtasks, without computing or
returning any data.
The return type of this kind of functions is void,
which means nothing.
For a void function, when the flow of control
reaches the end of the function body, the function
finishes and returns the control to the caller.

See change-fun.cc

c1117 lecture 4

41

Return statement

Note that when a return statement executes, the


control is transferred to the caller immediately, i.e.
anything after that return statement will not be
carried out.
Because of the behavior of return, we can omit
some else. See digitword.cc.
Return statement can also be used in void
function.

c1117 lecture 4

42

Arguments Vs parameters

Parameters are listed in the function heading and


are used in the body of the function definition.
Arguments are listed in parentheses after the
function name in a function call, acting as the
input to the function.
C++ is a strong-typing language. The type of
arguments passed to a function must match with
the type of the parameters specified.

Type mismatch between parameters and arguments can


be caught by compiler.

c1117 lecture 4

43

Examples

Which statements will be rejected by the compiler?


Why?
cout
//
cout <<
<< digit_to_word(
digit_to_word( 55 )) <<
<< endl;
endl;
// ???
???
cout
cout <<
<< digit_to_word(
digit_to_word( 22 ** 33 )) <<
<< endl;
endl; //
// ???
???
cout
cout <<
<< digit_to_word(
digit_to_word( 5.0
5.0 )) <<
<< endl;
endl; //
// ???
???
cout
cout <<
<< digit_to_word(
digit_to_word( eleven
eleven )) <<
<< endl;
endl; //
// ???
???
cout
cout <<
<< digit_to_word(
digit_to_word( -2
-2 )) <<
<< endl;
endl;
cout
cout <<
<< digit_to_word(
digit_to_word( 10
10 )) <<
<< endl;
endl;

//
// ???
???
//
// ???
???

digit_to_word(
digit_to_word( 22 );
);

//
// ???
???

c1117 lecture 4

44

Precondition & Postcondition

Precondition specifies the criteria that the


parameters must satisfy.

The caller of the function has to make sure that the


precondition is satisfied.

Postcondition shows the result when the function


finishes execution, provided that the precondition is
satisfied.
//
// pre:
pre: three
three sides
sides s1,
s1, s2,
s2, s3
s3 of
of aa valid
valid triangle
triangle
//
// post:
post: return
return the
the angle
angle opposite
opposite to
to s1
s1
double
double find_angle(double
find_angle(double s1,double
s1,double s2,double
s2,double s3)
s3)
{{ }}
//
// pre:
pre: nn >=
>= 00
//
// post:
post: return
return y,
y, s.t.
s.t. y*y
y*y == nn
double
double sqrt(double
sqrt(double n)
n) {{ }}

c1117 lecture 4

45

Local variables

Should all variables and parameters have different


names?
We can declare and use variables inside the
function body.

These variables are called local variables.


They are local to the function only and cannot be used
outside the function.
In fact, the variables declared in the main function, i.e.
in main(), are local variables of main, which cannot be
used in the user-defined functions.
Parameters of a function are the local variables of the
function.

c1117 lecture 4

46

Local variables
Function declaration
void
void print_output();
print_output();
int
int main(){
main(){
x, y and sum are the
int
local variables of the
int x,
x, y,
y, sum;
sum;
cin
main function. They can
cin >>
>> xx >>
>> y;
y;
only be used inside the
sum
sum == xx ++ y;
y;
main().
print_output();
print_output();
}}
void
void print_output(){
print_output(){
cout
cout <<
<< the
the sum
sum of
of your
your input
input is:
is:
<<
<< sum
sum <<
<< endl;
endl;
}}
Compiler will give error message that the
variable is not declared.
c1117 lecture 4

47

void
void print_output(int
print_output(int
int
int main(){
main(){
int
int x,
x, y,
y, sum;
sum;
cin
cin >>
>> xx >>
>> y;
y;
sum
sum == xx ++ y;
y;
print_output(sum);
print_output(sum);
}}
void
void print_output(int
print_output(int
cout
cout <<
<< the
the sum
sum of
of
<<
<< tt <<
<< endl;
endl;
}}
c1117 lecture 4

t);
t);
The parameter t is a
local variable of the
function print_output.

t){
t){
your
your input
input is:
is:

48

Scope of a variable

Scope of a variable is the portion of the program


that the variable is well-defined and can be used.

The scope of a local variable starts from its


declaration up to the end of the block.

It is not allowed to refer to variables beyond its scope.

A block is delimited by { and }.


Variables declared in an outer block can also be referred
to in the inner block.

We can declare variables with the same name as


long as they have different scopes.
See scope.cc as an example.

c1117 lecture 4

49

x, y and w are
the local
variables of the
function fn, their
scopes are
within fn.
The scope of k is
only within the
inner block.

c1117 lecture 4

int
int fn(int
fn(int x,
x, int
int y){
y){
int
int w;
w;
y, w and k are the
if(
if( xx >> y){
y){
local variables of the
int
k
=
w;
int k = w;
main function, same
...
...
variable names can be
}}
used in different
...
...
}}
scopes.
int
int main(){
main(){
int
int x,
x,
If same variable x is
int
y,
w,
k;
int y, w, k;
declared in the inner
...
...
block, the scope of
if(...){
if(...){
the first x is blocked
int
x;
int x;
in the scope of the
...
...
}}
second x.
}}
50

Global variables

We can declare variables outside any functions.


They can be accessed by any part of the program.
Experience shows that global variables caused a
lot of problem in maintenance.

Program bugs related to global variables are difficult to


trace.

If possible, you should avoid using global variables.

In particular, in the assignments of this course.

c1117 lecture 4

51

Global variables

Global variables are declared outside any functions.


Global variables can be used in any function definitions
that follows the variable declaration.
double
double x;
x;
int
int fn_2(...);
fn_2(...);
int
int fn_1(...)
fn_1(...)
{...}
{...}
int
int y;
y;
int
int main()
main()
{...}
{...}
int
int fn_2(...)
fn_2(...)
{...}
{...}

c1117 lecture 4

Variable x can
be used in fn_1,
fn_2 and the
main function.
Variable y can
only be used in
fn_2 and the
main function.
52

Potrebbero piacerti anche