Chapter 13 – Functions

Download Report

Transcript Chapter 13 – Functions

Chapter 14
Functions
Topics to Cover…








Functions
C Functions
Function Examples
Function Notes
main Function
Activation Records
Run-time Stack
Function Calls
BYU CS/ECEn 124
Variables and Operators
2
Functions
Functions


Smaller, simpler, subcomponent of program
Provides abstraction




Decomposition



hide low-level details
give high-level structure to program, easier to
understand overall program flow
enables separable, independent development
Functions break large computing tasks into smaller
ones.
Functions enlarge the set of elementary building blocks.
In other languages, called procedures, methods,
subroutines, ...
BYU CS/ECEn 124
Variables and Operators
3
Functions
Example of High-Level Structure
int main()
{
SetupBoard();
DetermineSides();
/* place pieces on board */
/* choose black/white */
/* Play game */
do
Structure of program
{
is evident, even without
WhitesTurn();
knowing implementation.
BlacksTurn();
} while (NoOutcomeYet());
}
BYU CS/ECEn 124
Variables and Operators
4
Functions
The Power of Functions

Decomposition



Functions break large computing tasks into smaller
ones.
Functions enlarge the set of elementary building
blocks.
Abstraction


Separate the “function” of a component from the
details of how it is accomplished.
The component can be used as a building block while
hiding the details in the function.
BYU CS/ECEn 124
Variables and Operators
5
Functions
Functions in C



Functions have been in all programming
languages since the very early days of computing.
Support for functions is provided directly in all
instruction set architectures.
C is heavily oriented around functions.




A C program is organized as a collection of functions.
Every C statement belongs to a function
All C programs start and finish execution in the function
main
Functions may call other functions which, in turn, call
more functions.
BYU CS/ECEn 124
Variables and Operators
6
C Functions
Parts of a C Function

The Declaration: Informs the compiler about the
function.

The Definition: The function body contained
inside braces {...}.

The Return Value: Calculated by the function,
and returned by a return statement in the body.

The Call: Arguments (actual parameters) from
the caller are transmitted to the function
parameters (formal parameters).
BYU CS/ECEn 124
Variables and Operators
7
C Functions
Parts of a C Function

The Declaration:
type name(type, type, ... );




Informs the compiler about the function
Only argument types needed
Ends in a semi-colon
The function prototype declares:



The function name
The type of the output value returned by the function
(void = nothing returned)
The types of input arguments that the function accepts as
input
BYU CS/ECEn 124
Variables and Operators
8
C Functions
Parts of a C Function

The Definition:
type name(type param, type param,...)
{ body }



The first line matches type in the declaration (but
without the semicolon)
The list of input arguments (formal parameters) by type
and name
The function body contained inside braces {...}
BYU CS/ECEn 124
Variables and Operators
9
C Functions
Parts of a C Function

The Return Value:
return expression;



Returned by a return statement in the body
Must match declaration return type
The Call:
name(expression, expression, ... )


Arguments (actual parameters) from the caller are
transmitted to the function parameters (formal
parameters)
Function definitions and function calls must having
matching prototypes.
BYU CS/ECEn 124
Variables and Operators
10
Function Examples
Example #1
#include <stdio.h>
function prototype
(declaration)
int addNumbers(int, int);
int main()
arguments
{
printf("\nResult is: %d", addNumbers(4, 5));
}
formal parameters
int addNumbers(int x, int y)
{
return (x+y);
}
BYU CS/ECEn 124
function definition
Variables and Operators
11
Function Examples
Example #2
#include <stdio.h>
void PrintBanner();
/* function declaration */
int main()
{
PrintBanner();
/* function call */
printf("\nA simple C program.");
PrintBanner();
/* function call */
}
void PrintBanner()
/* function definition */
{
printf("\n==================================");
}
/* no return value needed */
BYU CS/ECEn 124
Variables and Operators
12
Function Examples
Example #3
#include <stdio.h>
int Factorial(int n);
// function declaration
int main()
{
int number, answer;
...
answer = Factorial(number); // function call
...
}
int Factorial(int n)
// function definition
{
int i;
int result = 1;
for(i=1; i<=n; i++) result = result * i;
return result;
// return value to caller
}
BYU CS/ECEn 124
Variables and Operators
13
Function Notes
Function Notes

Minimal do-nothing function
void dummy( ) {}

Default return type is integer
three( ) { return 3; }
int three( ) { return 3; }



These are
the same
Function definitions cannot nest
Function arguments are local to the function
Function arguments are passed “by value”



Temporary (private) variables rather than the originals
Value could be a reference (such as with an array)
Call by value is an asset, not a liability
BYU CS/ECEn 124
Variables and Operators
14
Function Notes
Function Notes


The scope of a name (variable or function) is the part of
the program within which the name can be used.
A function prototype “extends” the scope of a function
and helps the compiler check function call syntax.
...
int xyz(int, int);
...
int xyz(int x, int y)
{
...
}
...
scope of xyz
with prototype
without prototype
/* end of file */
BYU CS/ECEn 124
Variables and Operators
15
main Function
The main Function

Must be present in every program
Is “called” by the operating system when program
is run
Returning from main exits the program

Is pre-declared as:


Don’t worry about what this means.
int main (int argc, char *argv[]);

The definition doesn’t have to match.
int main() { ... }
main() { ... }

These are OK
The return statement can be omitted.
BYU CS/ECEn 124
Variables and Operators
16
Activation Records
Implementing Functions in C


Functions are the C equivalent of subroutine in
assembly language.
Function calls involve three basic steps
1) Parameters from caller are passed to the callee.
Control is passed to callee.
2) Callee does the task
3) Return value is passed back to caller.
Control returns to the caller.

Functions must be caller-independent, i.e.
callable from any function.
BYU CS/ECEn 124
Variables and Operators
17
Activation Records
Activation Records






When a function is called, it needs to be activated, that is,
local variables must be given locations in memory.
An activation record for a function is a template of the
relative positions of its local variables in memory.
A frame is a local data storage area allocated on the stack
each time a function is called for the activation record.
Frame variables are for temporary storage and are lost
when the function returns.
The stack pointer is used for the frame pointer.
Data is stored and retrieved via indexed stack instructions.
mov.w
mov.w
BYU CS/ECEn 124
r12,0(sp) ; save parameter 1
0(sp),r12 ; return value
Variables and Operators
18
Run-time Stack
Run-time Stack Operation
main calls A
Program starts
Memory
A calls B
Memory
SP
func B
SP
func A
func A
main
main
SP
main
BYU CS/ECEn 124
Variables and Operators
19
Run-time Stack
Runtime Stack Operation
A returns to main
B returns to A
Memory
Memory
SP
func A
SP
main
BYU CS/ECEn 124
main
Variables and Operators
20
Activation Records
Stack Frames / Parameter Passing



Each function call creates a new stack frame.
The parameters of a called function are passed
to a function in a right to left order.
Up to four left most parameters are passed in
registers unless they are defined as a struct or
union type, in which case they are also passed
on the stack. The remaining parameters are
always passed on the stack.
BYU CS/ECEn 124
Variables and Operators
21
Activation Records
Stack Frames / Parameter Passing

Each function call creates a new stack frame.
High Address
Stack
Parameters
(When more than 4)
Return Address
Saved Registers (if any)
Frame or
Activation
Record
Local Variables
Stack Pointer (SP)
BYU CS/ECEn 124
Low Address
Variables and Operators
22
Activation Records
Activation Record (Frame)
Memory
int func(int a, int b)
{
int x, y, z;
…
return y;
}
Return Address
z
y
x
Symbol Table
Name
Type
Offset
Scope
a
int
0(SP)
func
b
int
2(SP)
func
x
int
4(SP)
func
y
int
6(SP)
func
z
int
8(SP)
func
BYU CS/ECEn 124
Bookkeeping Info
Local variables
b
SP 
Variables and Operators
a
23
Run-time Stack
Stack Frames / Parameter Passing

Example:
int func(a, b, c, d, e, f)
{
int x, y, z;
x = 1;
y = 2;
z = 3;
return a+b+c+d+e+f+x+y+z;
}
int main()
{
func(10, 20, 30, 40, 50, 60);
return 0;
}
f
e
z
y
x
d
c
b
SP  a
60
50
Return adr
3
2
1
40
30
20
10
BYU CS/ECEn 124
0x0012(SP)
0x0010(SP)
0x000c(SP)
0x000a(SP)
0x0008(SP)
0x0006(SP)
0x0004(SP)
0x0002(SP)
0x0000(SP)
main:
0x8762:
0x8764:
0x876a:
0x8770:
0x8774:
0x8778:
0x877c:
0x8780:
0x8784:
0x8786:
0x8788:
0x853c:
0x8540:
0x8544:
0x8548:
0x854c:
0x8550:
0x8554:
0x8558:
0x855e:
0x8562:
0x8564:
0x8568:
0x856c:
0x8570:
0x8574:
0x8578:
0x857c:
0x8580:
0x8584:
8221
40B1 0032 0000
40B1 003C 0002
403C 000A
403D 0014
403E 001E
403F 0028
12B0 853C
430C
5221
4130
func:
8031 000E
4F81 0006
4E81 0004
4D81 0002
4C81 0000
4391 0008
43A1 000A
40B1 0003 000C
411C 0002
512C
511C 0004
511C 0006
511C 0010
511C 0012
511C 0008
511C 000A
511C 000C
5031 000E
4130
Variables and Operators
SUB.W
MOV.W
MOV.W
MOV.W
MOV.W
MOV.W
MOV.W
CALL
CLR.W
ADD.W
RET
#4,SP
#0x0032,0x0000(SP)
#0x003c,0x0002(SP)
#0x000a,R12
#0x0014,R13
#0x001e,R14
#0x0028,R15
#func
R12
#4,SP
SUB.W
MOV.W
MOV.W
MOV.W
MOV.W
MOV.W
MOV.W
MOV.W
MOV.W
ADD.W
ADD.W
ADD.W
ADD.W
ADD.W
ADD.W
ADD.W
ADD.W
ADD.W
RET
#0x000e,SP
R15,0x0006(SP)
R14,0x0004(SP)
R13,0x0002(SP)
R12,0x0000(SP)
#1,0x0008(SP)
#2,0x000a(SP)
#0x0003,0x000c(SP)
0x0002(SP),R12
@SP,R12
0x0004(SP),R12
0x0006(SP),R12
0x0010(SP),R12
0x0012(SP),R12
0x0008(SP),R12
0x000a(SP),R12
0x000c(SP),R12
#0x000e,SP
24
Function Calls
Function Calls

Caller




If more than 4 arguments, push function arguments on
stack (right-to-left)
Put 1st argument in R12, 2nd argument in R13,…
Transfer control to function with call instruction
Callee



Create activation record on the stack
Save arguments in activation record
Save any callee-saved registers that are altered in
activation record.
BYU CS/ECEn 124
Variables and Operators
25
Function Calls
The Return

Callee





Put return value in R12
Restore any saved registers
Pop activation record
Return control to caller (RET = mov.w @sp+,pc)
Caller

Return value is in R12
BYU CS/ECEn 124
Variables and Operators
26
Function Calls
Activation Record (Frame)
Memory
int main()
{
int n;
int m;
…
m = func(n, 10);
…
}
int func(int a, int b)
{
int x, y, z;
…
return y;
}
BYU CS/ECEn 124
Return Address
m
n
Local
variables
Activation
Record for
main
Local
variables
Activation
Record for
func
Return Address
z
y
x
b
SP 
a
Variables and Operators
27
BYU CS/ECEn 124
Variables and Operators
28