• As long as you do not change the interface, your function can be reused.
22 Why do we use Functions? • There are two major reasons: 1. A large problem can be solved easily by breaking it up into several small problems and giving the responsibility of a set of functions to a specific programmer. • It is easer to write two 10 line functions than one 20 line one and two smaller functions will be easier to read than one long one. 2. They can simplify programming tasks because existing functions can be reused as the building blocks for new programs. • Really useful functions can be bundled into libraries.
23 Procedural Abstraction • Procedural Abstraction – A programming technique in which a main function consists of a sequence of function calls and each function is implemented separately. • All of the details of the implementation to a particular subproblem is placed in a separate function. • The main functions become a more abstract outline of what the program does. When you begin writing your program, just write out your algorithm in your main function. Take each step of the algorithm and write a function that performs it for you. • Focusing on one function at a time is much easier than trying to write the complete program at once.
24 Reuse of Function Subprograms • Functions can be executed more than once in a program. Reduces the overall length of the program and the chance of error. • Once you have written and tested a function, you can use it in other programs or functions.
25 Common Programming Errors • Remember to use a #include preprocessor directives for every standard library from which you are using functions. • Place prototypes for your own function subprogram in the source file preceding the main function; place the actual function definitions after the main function. • The acronym NOT summarizes the requirements for argument list correspondence. Provide the required N umber of arguments Make sure the O rder of arguments is correct Make sure each argument is the correct T ype or that conversion to the correct type will lose no information. • Include a statement of purpose on every function you write. • Also be careful in using functions that are undefined on some range of values.
- Spring '10
- Function Subprograms