1 / 27

Functions

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 many functions printf () is a function that causes data to be printed on the screen . s canf () read data from a keyboard

Download Presentation

Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Functions

  2. Motivation What 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

  4. Example Suppose, for example, that you want to write a program that does the following: • Read in a list of numbers such as [5, 6, 1, 7, 2, 4, 3] • Sort the numbers [1, 2, 3, 4, 5, 6 ,7] • Find their average 4 • 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

  7. Example: starbar() function Many nested function class are possible String constants %s is used to print strings

  8. 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 Header Body Header function_typefunction_name( parameter list ) { local variable declaration; executable statment1; executable statement2; … return statement; } Body

  9. Function names and usage rules Both function names and variables are considered identifies and therefore they must adhere to the rules for identifiers. Functions Variables OK OK WRONG WRONG

  10. 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 • If function does not return any value, use typevoid. The following function header indicates that a defined function takes two type intarguments but that returns a type double value.

  12. 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 …

  13. Function prototypes Without function prototype With 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.

  14. Passing arguments to function example * Function strlen() returns number of characters in a string Example: intn = strlen(“Hello”); // n will be 5

  15. Calling a Function with Arguments Declaration on an ANSI function prototype: We can omit variable names in the 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

  17. Returning a Value from a Function with return How can we simplify this program? Functions can be used as a part of an expression

  18. The Black-Box Viewpoint • Taking a black-box viewpoint of show_n_char(char ch, intnum), 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, intn) return result

  19. CPU implementation of function calls: Stack • To understand how processor treats function calls, we need to introduce stack memory. • Astack 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". Recall that eaxis a 32 bit register (small and fast memory inside CPU) • A stack is also known as a LIFO queue (Last In First Out).

  20. CPU implementation of function calls: push and pop The current top of the stack is pointed to by the espregister. ebp ebp is pointing to the base of the stack Stack grows from the location where espis pointing to.

  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 esplocation in the memory. Consider the following function definition and a function call oversimplified _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) This will create the following assembly code copied to stack Similar to jmp It turns out that the function arguments are all passed on the stack!

  23. Recursion • 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

  24. Recursion Note that each level of recursion uses its own privaten variable

  25. Tail Recursion Tail 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.

  26. Recursion and Reversal The function prints the binary equivalent of a decimal integer. putchar( r ? '1' : '0');

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

More Related