Beruflich Dokumente
Kultur Dokumente
Functions
Introduction
A function is a self-contained block of statements that perform a coherent task of some kind. Derived data types in C Classifications:
Library functions User defined functions
main() is an example of user defined function Need for user defined functions
Advantages
1. It facilitates top-down modular programming
Function main
Function italy
Function india
Example
Advantages..
2. The length of a source program can be reduced by using functions at appropriate places 3. It is easy to locate and isolate a faulty function for further investigations 4. A function may be used by many other programs. This means that a C programmer can build on what others have already done.
Three Elements
1. Function Definition
is an independent program module that is specially written to implement the requirements of the function function invoking also known as function prototype
2. Function Call
3. Function declaration
Example
Points to be noted
Any C program contains at least one function . if a program contains only one function, it must be function main() In a C program if there are more than one functions present, then one of these functions must be main(), because program execution always begins with main() There is no limit on the number of functions that might be present in a C program
Points to be noted
Each function in a program is called in the sequence specified by the function calls in main() After each function has done its thing, control returns to main(). When main() runs out of function calls, the program ends
Example
Default type of a function is int
Example
calsum (x, y, z) int x, y, z; { int d; d =x+y+z; return(d); }
calsum (x, y, z) int x, y, z; { return(x+y+z); }
Function call
Actual Argument
Formal Argument
Important Note
Actual arguments can be an expression If the actual parameters are more than the formal parameters, the extra actual arguments will be discarded If the actual arguments are less than the formals, the unmatched formal arguments will be initialized to some garbage. Any mismatch in data types may also result in some garbage values
Function Declaration
A function declaration or function prototype consists of four parts
Function type (return type ) Function name Parameter list Terminating semicolon
Function-type function-name ( parameter list ) ;
Examples
1. int mul (int, int); int mul (int a, int b); mul (int a, int b); mul (int, int); 2. void mul (void );
Function Declaration
A prototype declaration may be placed in two places in a program
Above all the function (including main() ) Global prototype Inside a function definition Local prototype
Example
Global Prototype
Local Prototype