USER-DEFINED FUNCTIONS - Mr. S. JEEVANANDHAM M.C.A., M.Phil .,PGDCA ., Assistant Professor, Department of Computer Science, M. G. R. College, Hosur .
INTRODUCTION • C functions can be classified into two categories Library functions – User-defined functions
LIBRARY FUNCTIONS – Library functions are not required to be written by – printf and scanf belong to the category of library function – sqrt , cos , strcat , etc are some of library functions
USER-DEFINED FUNCTIONS – User-defined functions has to be developed by the user at the time of writing a program – A user-defined functions can later become a part of the C program library – main is an example of user-defined functions
ELEMENTS OF USER-DEFINED FUNCTIONS There are three elements related to functions – Function definition – Function call – Function declaration • The function definition is an independent program module that is specially written to implement the requirements of the function. • To use this function we need to invoke it at a required place in the program. This is known as the function call . • The program that calls the function is referred to as the calling program or calling function . • The calling program should declare any function that is to be used later in the program. This is known as the function declaration or function prototype .
FUNCTION DECLARATION A function declaration consists of four parts – Function type (return type) – Function name – Parameter list – Terminating semicolon Syntax, Function-type function-name (parameter list ); Example, void display( int );
FUNCTION DEFINITION A function definition, also known as function implementation shall include the following elements; – Function name; – Function type; – List of parameters; – Local variable declaration; – Function statements; and – A return statement .
CALLING A FUNCTION A function can be called by simply using the function name in a statement When the function encounters a function call, the control is transferred to the function mul ( x,y )
Example program main() { int p; p = mul (10,5); printf ("%d\n", p); } int mul ( int x,int y) { int p; /*local variables*/ p = x * y;/* x = 10, y = 5*/ return(p); }
CATEGORY OF FUNCTIONS Category 1: Functions with no arguments and no return values Category 2: Functions with arguments and no return values Category 3: Functions with arguments and one return values Category 4: Functions with no arguments but return a value
Function with no arguments and with return Values Main() data_type func1() { { ………….. …………… ………….. …………… C=func1(); …………… ………….. ……………. …………... Return(a); }
RETURNING A VALUE C function returns a value of the type int as a default case when no other type is specified explicitly. return(value); Return the integer value of sum