Lec 7 - Functions
Lec 7 - Functions
2
Divide and Conquer Approach
3
Functions
4
Example: Function
5
Modularizing a Program
7
Function
8
Function
9
Components of Function Use
11
1. Function Declaration/Prototype
12
Function Declaration/Prototype
13
Alternative Function Declaration
14
2. Function Definition
15
Example of User-defined Function
16
Function Definition
19
Function Definition
20
Function Definition
21
Return Type
22
Return Statements
23
3. Function Call
24
Example 1
25
Example 2
26
Example 3
27
Example 3:
28
Example 4: gcd()
29
Example 4: gcd()
30
Parameters/Arguments
➢ Formal parameters
o In function declaration
o In function definition's header
o 'Placeholders' for data sent in
o 'Variable name' used to refer to
data in definition of function
➢ Actual arguments
o In function call
➢ X is formal parameter
➢ 5 is argument
31
Passing Arguments
32
Passing Arguments: Passing by Value
33
Passing Arguments: Passing by Value
34
Passing Arguments: Passing by Value
35
Passing Arguments: Passing by
Reference/Pointer/Address
36
Passing Arguments: Passing by
Reference/Pointer/Address
37
Passing Arguments: Passing by Value &
Pointer
38
Passing Arguments: Passing by Value &
Pointer
39
Return Statement
40
Return Statement
41
Return Statement
42
Functions Calling Functions
43
Declaring Void Functions
44
Declaring Void Functions
➢ Nothing is returned
o Void functions cannot have return statement with an
expression
▪ Will return at end of function
o Non-void functions must have return statement with an
expression
➢ Example definition:
45
Calling Void Functions
46
Calling Void Functions
47
Function Documentation
48
Scope of Identifier Names
49
Scope of Identifier Names
50
Global Scope
51
Global Constants and Global Variables
➢ Global variables?
o Possible, but SELDOM-USED
o Better alternative is to use parameters
o Dangerous: no control over usage!
52
Block Scope
53
Lifetime
54
Static & Lifetime
55
Math Library Functions
56
More Math Library Functions
57