Functions
Functions
FUNCTIONS
FUNCTIONS
STATIC VARIABLES
2
INTENDED LEARNING OUTCOMES (ILOs)
To
understand To identify
To identify
how the use of
the scope of
functions static
variables
operate variables
3
1
FUNCTIONS
4
FUNCTIONS
5
FUNCTIONS
6
FUNCTION DEFINITION
7
FUNCTION DEFINITION
8
FUNCTION DEFINITION
9
FUNCTION DEFINITION
10
FUNCTION DEFINITION
11
FUNCTION DEFINITION
12
FUNCTION DECLARATION
13
FUNCTION DECLARATION/PROTOTYPE
14
FUNCTION DECLARATION/PROTOTYPE
15
FUNCTION CALL
16
FUNCTION CALL
17
FUNCTION CALL
18
FUNCTIONS
19
FUNCTIONS
▪ NB: Note that when the function is called we stop whatever we are
doing and go to where the function has been defined in our
program and return to the point we left off after the function has
been executed.
20
FUNCTIONS
21
FUNCTIONS
22
FUNCTIONS - EXAMPLE
23
FUNCTIONS - EXAMPLE
24
FUNCTIONS - EXAMPLE
▪ From the syntax we can then reckon that line 2 contains the
function declaration, line 6 contains the function call and lines 10
to 16 contain the function definition.
25
FUNCTIONS - EXAMPLE
26
FUNCTIONS - EXAMPLE
27
FUNCTIONS - EXAMPLE
28
FUNCTIONS - EXAMPLE
▪ So now that we are in the definition (line 10). We copy the value in x from
the function call (i.e. 10.25) into the variable rad. So now rad has a value
10.25.
▪ So on line 12 we declare a variable a.
▪ On line 13, we assign a to the result of 3.142*rad*rad (formula for
calculating the area of a circle) which would result in 330.106
▪ Then on line 15 we return the value in a to where the function was called
(i.e. line 6)
29
FUNCTIONS - EXAMPLE
30
FUNCTIONS - EXAMPLE
31
FUNCTIONS - EXAMPLE
32
2
LOCAL AND GLOBAL
VARIABLES
33
LOCAL AND GLOBAL VARIABLES
34
LOCAL AND GLOBAL VARIABLES - EXAMPLES
35
LOCAL AND GLOBAL VARIABLES
50
20
50
End
36
LOCAL AND GLOBAL VARIABLES
▪ From the code x was declared outside all functions thus making x
a global variable.
▪ y and z were declared within the main function and funct1 function
respectively thus making them local variables.
37
LOCAL AND GLOBAL VARIABLES
38
3
STATIC LOCAL
VARIABLES
39
STATIC LOCAL VARIABLES
40
STATIC LOCAL VARIABLES
41
NON-STATIC LOCAL VARIABLE EXAMPLE
43
STATIC LOCAL VARIABLE EXAMPLE
45
STATIC LOCAL VARIABLE EXAMPLE
46
THANKS!
Any questions?
You can find me at
elielkeelson@gmail.com & ekeelson@knust.edu.gh
47