Session 9

| Functions Session 9 Objectives Explain the use of functions Explain the structure of a function Explain function declaration and function prototypes Explain the different types of variables Explain how to call functions Call by Value Call by Reference Explain the scope rules for a function Explain functions in multifile programs Explain Storage classes Explain function pointers Functions Functions are generally used as abbreviations for a series of instructions that are to be executed more than once Functions are easy to write and understand Debugging the program becomes easier as the structure of the program is more apparent, due to its modular form Programs containing functions are also easier to maintain, because modifications, if required, are confined to certain functions within the program A function is a self-contained program segment that carries out a specific, well-defined task The Function Structure The general syntax of a function in C is : The type_specifier specifies the data type of the value, which the function will return. A valid function name is to be assigned to identify the function Arguments appearing in parentheses are also termed as formal parameters. Arguments of a function The program calculates the square of numbers from 1 to 10 The data is passed from the main() to the squarer() function The function works on data using arguments Actual Arguments Formal Arguments Returning from the function It transfers the control from the function back to the calling program immediately. Whatever is inside the parentheses following the return statement is returned as a value to the calling program. Data Type of a Function The type_specifier is not written prior to the function squarer(), because squarer() returns an integer type value The type_specifier is not compulsory if an integer type of value is returned or if no value is returned However, to avoid inconsistencies, a data type should be specified Invoking a Function A semicolon is