1 / 12

CS1061 C Prgramming Lecture 11: Functions

CS1061 C Prgramming Lecture 11: Functions. A. O’Riordan, 2004. Functions. Functions modularize a program All variables declared inside functions are local variables known only in the function defined Parameters communicate information between functions ’ local variables

armen
Download Presentation

CS1061 C Prgramming Lecture 11: 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. CS1061 C PrgrammingLecture 11: Functions A. O’Riordan, 2004

  2. Functions • Functions modularize a program • All variables declared inside functions are local variables known only in the function defined • Parameters communicate information between functions’ local variables Benefits of functions • Divide and conquer - manageable program development • Software reusability - use existing functions as building blocks for new programs • Abstraction - hide internal details (library functions) • Avoid code repetition

  3. Functions (2) Every C program has to have at least one function called main(). This is the first function that is executed. This function may then call other functions. It is conventional to place the main() function at the start of the program followed by all the other functions in the file. It is universally considered good software engineering practice to keep functions short. Long functions can be difficult to understand. A rule of thumb is to keep functions shorter than 50 lines, except in exceptional circumstances.

  4. Form of a Function A function has the form: return_type function_name (<parameters>){ <local variable declarations> <statements> } Firstly we have the function name (and return type and parameters). Note that even if a function returns a value, the caller does not have to use it. Any C function may have parameters, which is a mechanism for passing extra information to a function. Then you have the body of the function enclosed by curly braces {}. In the body you can have zero, one or more local variable declarations, followed by zero, one or more statements.

  5. Example Program with Two Functions Here is an example where main() calls another function printMessage(). #include <stdio.h> void printMessage();/* prototype */ int main(){ printMessage(); } void printMessage(){ printf("Function has been called\n"); return; }

  6. Prototypes • Functions need to be declared before they are defined, printMessage() is declared in the second line of the program above • The declaration informs the compiler about the details of the function, such as the function name, the return type and the number and type of each argument. • In C, function declarations are called prototypes. • C is case sensitive so a function called MyFunction is different than a function called myfunction. • The return type is the data type of the result (default int).Use void to indicate that a function returns nothing.

  7. Functions with Parameters (2) • Most real function take parameters (sometimes called formal parameters). The values that are supplied to these parameters are called arguments (or actual arguments). The name of a function together with its parameter list is called its signature. • A parameter list consists of comma-separated variables. Types for each variable must be specified. • The number and order of variables is important, e.g. passing an incorrect argument list, such as passing an argument of the wrong type, will be caught by the compiler. • In function prototypes variable names may be omitted.

  8. Functions with Parameters (2) Here is a function that accepts three parameters, the first an int, the second a float and the third a char. void myFunction( int a, float b, char c) { printf("The parameters are %d, %f, %c\n", a, b, c); } Valid calls to our function above could look like any of the following (assuming x is an int with value 10, y is a float with value 10.0 and z is a character with value ‘F’). All three calls below pass the same values. myFunction( x, y, z ); myFunction( 10, 10.0, ‘F' ); myFunction( x, x, 70 ); /* x implicitly cast to a float, 70 is ASCII for ‘F’ */

  9. Returning a Value #include<stdio.h> typedef int max_speed; max_speed get_faster(max_speed, max_speed); int main(){ max_speed bmw=240, subaru=230; printf("The faster car can go %dkph\n", get_faster(bmw,subaru)); } max_speed get_faster(max_speed car1, max_speed car2){ if (car1 >= car2) return(car1); return(car2); }

  10. Function with Multiple Returns It is possible for a function to have multiple return statements. int validate_input(char operator) { switch(operator){ case ‘+’: case ‘-‘: return 1; case ‘*’: case ‘/’: return 2; default: return 0; } }

  11. Recursion Recursive functions - functions that call themselves Example: factorials 5! = 5 * 4 * 3 * 2 * 1 Notice that5! = 5 * 4! so we can compute factorials recursively Choice between performance (iteration) and elegance (recursion) Recursion v. Iteration RepetitionIteration: explicit loop Recursion: repeated function calls TerminationIteration: loop condition fails Recursion: base case recognized

  12. Recursion Example A recursive function calls itself either directly or indirectly. The factorial function can be written as a recursive function: int fac(int n){ if (n == 1) return 1; return (n * fac(n-1)); } A recursive function must always have a stopping condition, otherwise execution goes on infinitely. In the fac() example, the stopping condition is when n is equal to 1. The fact that each successive call to fac() has a smaller argument ensures convergence to the stopping condition.

More Related