Date post: | 19-Jan-2016 |
Category: |
Documents |
Upload: | baldwin-rose |
View: | 216 times |
Download: | 0 times |
Functions
MotivationWhat is a function?
A function is a self-contained unit of program code designed to accomplish a particular task.
We already used many functions printf() is a function that causes data to be printed on the screen. scanf() read data from a keyboard Math functions
sqrt() exp() sin() cos() tan()
3
Motivation
Why should you use functions? Function save you from repetitious programming (save time and
space) Using a function is worthwhile because it makes a program more
modular, hence easier to read and easier to change or fix.
Main program
Function A Function B Function C
F1 F2
Example
Suppose, for example, that you want to write a program that does the following:
Read in a list of numberssuch as [5, 6, 1, 7, 2, 4, 3]
Sort the numbers[1, 2, 3, 4, 5, 6 ,7]
Find their average4
Print a bar graph
A function can be thought as a "black box" defined in terms of the information that goes in (its input) and the value or action it produces (its output).
5
What do we need to know about functions?
How to define functions properly How to call functions up for use. How to set up communication between functions.
6
Example: starbar() function
Example: starbar() function
%s is used to print strings
String constants Many nested function class are possible
Definition of functions Function definition include six elements grouped in two parts
function type; function name; list of parameters; local variable declarations function statements a return statement
Body
Hea
der
function_type function_name ( parameter list ){
local variable declaration;executable statment1;executable statement2;…return statement;
}
Body
Header
Function names and usage rulesBoth function names and variables are considered identifies and therefore they must adhere to the rules for identifiers.
Variables FunctionsOK OK
WRONGWRONG
Function types and arguments
Similar as variables have types, functions also have types
A function may or may not have parameter. Type of each parameter have to by specified.
Functions also can return values
or
11
Function types and arguments
The following function header indicates that a defined function takes two type int arguments but that returns a type double value.
If function does not return any value, use type void.
Function prototypes For functions the declaration needs to be before the first call of the
function. A full declaration (prototype) includes the return type and the
number and type of the arguments. The function prototype is function header with semicolon at the end.
Function prototypes are usually combined in to a header file .h
math. h
…
Function prototypesWith function prototype Without function prototype
Having the prototype available before the first use of the function allows the compiler to check that the correct number and type of arguments are used in the function call and that the returned value, if any, is being used reasonably.
Passing arguments to function example
* Function strlen() returns number of characters in a stringExample:int n = strlen(“Hello”); // n will be 5
Calling a Function with Arguments
We can omit variable names in the prototype:
Declaration on an ANSI function prototype:
We give ch and num values by using actual arguments in the function call. Consider the first use of show_n_char().
The actual argument can be a constant, a variable, or an even more elaborate expression
16
Calling a Function with Arguments
copy 25 to variable number
Returning a Value from a Function with return
Functions can be used as a part of an expression
How can we simplify this program?
The Black-Box Viewpoint
Taking a black-box viewpoint of show_n_char(char ch, int num), the input is the character to be displayed and the number of times to be repeated.
The input is communicated to the function via arguments. This information is enough to tell you how to use the function in main().
The fact that ch, num, and count are local variables private to the show_n_char() function is an essential aspect of the black box approach. If you were to use variables with the same names in main(), they would be separate, independent variables.
show_n_char()internal variables
ch, num, count (char c, int n) return result
19
CPU implementation of function calls: Stack
To understand how processor treats function calls, we need to introduce stack memory.
A stack is a data structure that stores data values contiguously in memory.
An access (read or write) data is performed only at the "top" of the stack. To read from the stack is said "to pop" and to write to the stack is said "to push".
A stack is also known as a LIFO queue (Last In First Out).
Recall that eax is a 32 bit register (small and fast memory inside CPU)
20
CPU implementation of function calls: push and pop
The current top of the stack is pointed to by the esp register.
Stack grows from the location where esp is pointing to.
ebp
ebp is pointing to the base of the stack
21
CPU implementation of function calls: Data allocation
There are two areas in the computer memory where a program can store data. The stack: linear LIFO buffer that allows fast allocations and
deallocations, but has a limited size. Stacks are used to pass variables to function or store local variables (variable declare inside functions).
The heap: typically a non-linear data storage area, where allocations/deallocations are performed more slowly. The heap is used to allocate large chunks of memory.
22
CPU implementation of function calls: Stack Frames
The idea behind a stack frame is that each function can act independently of its location on the stack, and each function can act as if it is the top of the stack.
When a function is called, a new stack frame is created at the current esp location in the memory.
This will create the following assembly code
Consider the following function definition
Similar to jmp
It turns out that the function arguments are all passed on the stack!
_MyFunction2:| 2 | [ebp + 16] (3rd function argument)| 5 | [ebp + 12] (2nd argument)| 10 | [ebp + 8] (1st argument)| RA | [ebp + 4] (return address)| FP | [ebp] (old ebp value)
oversimplified
copied to stack
and a function call
C permits a function to call itself. This process is termed recursion.
Recursion often can be used where loops can be used.
It's vital that a recursive function contain something to halt the sequence of recursive calls
Recursion
24
Recursion
Note that each level of recursion uses its own private n variable
Tail RecursionTail recursion acts like a loop. The recursive call is at the end of the function, just before the return statement.
n! = n x (n-1)!
Although the recursive call to rfact() is not the last line in the function, it is the last statement executed when n > 0, so it is tail recursion.
Recursion and ReversalThe function prints the binary equivalent of a decimal integer.
putchar( r ? '1' : '0');
Recursion Pros and Cons
+ recursion offers the simplest solution to some programming problems.
- some recursive algorithms can rapidly exhaust a computer's memory
The Fibonacci function allocates a variable called n and evokes itself twice, creating two more variables called n at the second level of recursion.Each of those two calls generates two more calls, requiring four more variables called n at the third level of recursion, for a total of seven variables. This processes results in a enormous number of allocated variables.
Fibonacci(40)
Fibonacci(38) Fibonacci(39)
Fibo (36) Fibo (37) Fibo (37) Fibo (38)
F(34) F(35) F(35) F(36) F(35) F(36) F(36) F(37)