functions. motivation what is a function? a function is a self-contained unit of program code...

27
Functions

Upload: baldwin-rose

Post on 19-Jan-2016

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

Functions

Page 2: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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()

Page 3: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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

Page 4: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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).

Page 5: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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.

Page 6: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

6

Example: starbar() function

Page 7: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

Example: starbar() function

%s is used to print strings

String constants Many nested function class are possible

Page 8: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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

Page 9: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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

Page 10: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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

Page 11: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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.

Page 12: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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

Page 13: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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.

Page 14: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

Passing arguments to function example

* Function strlen() returns number of characters in a stringExample:int n = strlen(“Hello”); // n will be 5

Page 15: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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

Page 16: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

16

Calling a Function with Arguments

copy 25 to variable number

Page 17: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

Returning a Value from a Function with return

Functions can be used as a part of an expression

How can we simplify this program?

Page 18: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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

Page 19: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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)

Page 20: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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

Page 21: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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.

Page 22: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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

Page 23: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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

Page 24: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

24

Recursion

Note that each level of recursion uses its own private n variable

Page 25: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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.

Page 26: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

Recursion and ReversalThe function prints the binary equivalent of a decimal integer.

putchar( r ? '1' : '0');

Page 27: Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used

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)