Functions When programs become too large and complex and as a result the task of debugging, testing, and maintaining becomes difficult then C provides a most striking feature known as user defined function to solve this problem. If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. These independently coded programs are called sub programs that are much easier to understand, debug and test. In C these sub programs are referred to as functions. A function is a self contained block of statements that perform a coherent task of some kind. Or A function is a self contained block of code that is designed to perform a specific task. Once a function has been designed and packed then it can be treated as a separate entity/module/component or black box that takes some data from the main program and returns a value. The inner details of operation are invisible to the rest of the program. All that the program knows about a function is: What goes in and what comes out. Every C program is a collection of these functions Few Facts About Functions: 1. Functions can be either library functions or user defined functions. For example printf( ), scanf( ) are library functions. And user defined functions may be of any name like message( ), show( ) or etc. 2. There can be any number of functions in a program and any function can call any other function any number of times. 3. The order in which the function get called and the order in which they are defined in a program need not necessarily be same. 4. The use of user defined functions allows a large program to be broken down into a number of smaller self contained component/blocks, each of which has a definite purpose. Advantages of Functions: There are several advantages of using functions in a program like:- 1. Writing user defined functions avoids rewriting the same code again and again 2. Functions makes debugging or error rectification very easy 3. Functions make testing very easy. 4. Functions provide a main concept of reusability of same code again and again. 5. Functions divide a large program or problem into a number of small sub programs or sub problems User Defined Functions Page: 1 By Hemant Kumar
For example: here a small program is given below This program will print the following output: -------------------------------------------------------------------------- This illustrates the use of C functions -------------------------------------------------------------------------- The above program contains two user defined functions: main() function and printline() function Elements of User Defined Functions: In order to make use of a user defined functions, we need to establish three elements that are related to functions. 1. Function definition 2. Function call 3. Function declaration The function definition is an independent program module that is specially written to implement the requirements of the function. In order to use this function we need to invoke it at a required place in the program. This is known as function call. The program that calls the function is referred to as the calling function. The calling program should declare any function (like variable declaration) that is to be used later in the program. This is known as the function declaration or function prototype. User Defined Functions Page: 2 By Hemant Kumar
Elements of User Defined Functions: A function definition is also known as function implementation. It includes the following elements: 1. Function name 2. Function s return type 3. List of parameters 4. local variable declaration 5. Function statements (or function body or logical statement) 6. A return statement All the six elements are grouped into two parts Function header (first three elements) Function body (second three elements) A general format of a function definition to implement these two parts is given below: The first line Function_type function_name(parameter list) is known as function header. And the statement within the opening and closing braces constitute the function body, which is a compound statement. The parameters which are declared in function header are known as formal parameters. The parameters which are passed in function calling are known as actual parameters. Types of User Defined Functions: User defined functions are of the following types depending upon the parameters are passed or not and whether a value is returned or not. 1. Function with no arguments and no return values 2. Function with arguments and with no return values 3. Function with arguments and with one return value 4. Function with no arguments but return a value 5. Function that return multiple values. User Defined Functions Page: 3 By Hemant Kumar
Function with No arguments and No return type: When a function has no arguments, it does not receive any value or data from calling function. Similarly, when it does not return a value, the calling function does not receive any data from the called function. For example: The above function void printline(void) does not take any argument that is why its argument list is void. And does not return any value that is why its return type is void. Function with arguments but No return type: When a function takes some arguments, it receives values or data from calling function or from main function. When it does not return a value, the calling function does not receive any data from the called function. The parameters which are passed in function calling are known as actual parameters and the parameters which are declared in function definition are known as formal parameters. When a function call is made, these actual parameters and formal parameters must be matched in type, sequence, and number. For example: User Defined Functions Page: 4 By Hemant Kumar
The above function void printline(char ch) takes one argument that is why its argument list is char ch. And does not return any value that is why its return type is void. Some more examples are given Function with arguments with returning values: Functions with arguments and with returning values: receive input values or data from calling function (or from main function) and return the calculated value as output to the calling function (or to the main function) for the further processing. This concept uses the actual parameters in function calling and formal parameters in function definition and they must be equal in each type like types, numbers, and sequence. For example: Functions with No arguments But return values: The function which do not take any argument or parameter i.e. they don t take any input from main or calling function but they take input data directly from user or they use directly given values with the help of local variables and return the calculated or operated value as output to the calling function in main. Sometimes such functions are also known as utility functions because they provide some certain operated calculated value each time. A typical example of this type as we are discussing is getchar function which is declared in the header file <stdio.h>. The getchar User Defined Functions Page: 5 By Hemant Kumar
function has no parameters but it returns an integer type data that represents a character. For example review the following code segment: Functions with returning Multiple values (i.e. Call By Reference) All the above discussed functions are the functions which can return maximum one value only. This is because a return statement can return only one value at a time. But however we want to get more information from the function, we can achieve it using actual arguments not only to send the information to the function definition but also get back information from the function definition. The arguments that are sued to send out information are called output parameters. The mechanism of sending back information through arguments is achieved using what are known as the address operator (&) and indirection operator (*). For example: - The actual arguments x and y are input arguments, s and d are output arguments. In the function call, while we pass the actual values of x and y to the function we pass the address of locations or variables where the values of s and d are stored in the memory. (That is why, the indirection operator (*) is known as address operator). User Defined Functions Page: 6 By Hemant Kumar
The indirection operator * in the declaration of sum and diff in the header of function indicates these variables are to store addresses, not actual values of variables. Now, the variables sum and diff point to the memory locations of s and d respectively. The variables *sum and *diff are known as pointers and sum and diff as pointer variables. The use of pointer variables as actual parameters for communicating data between functions is called pass by pointer or call by address or call by reference. Rules for Call By Value (or Pass by Pointers) Nested Functions (or Nesting of Functions) C allows nesting of functions. Main function can call a function func1, which calls func2, which calls func3... and so on. There is in principle no limit as to how deeply functions can be nested. For example: User Defined Functions Page: 7 By Hemant Kumar
Recursion In C, it is possible for the functions to call themselves. A function is called recursive if a statement within the body of a function calls the same function. Sometimes it is called circular definition ; recursion is the process of defining something in terms of itself. Recursion is the process in which a function calls itself in it until a specific condition is satisfied or when a function calls to itself within its definition until a specific condition is satisfied this process is known as recursion and such functions are known as recursive functions. Assume that the number entered through scanf( ) is 3. Using figure give below visualizes what exactly happens when the recursive function rec( ) gets called. Go through the figure carefully. The first time when rec( ) is called from main( ), x collects 3. From here, since x is not equal to 1, the if block is skipped and rec( ) is called again with the argument ( x 1 ), i.e. 2. This is a recursive call. Since x is still not equal to 1, rec( ) is called yet another time, with argument (2-1). This time as x is 1, control goes back to previous rec( ) with the value 1, and f is evaluated as 2. User Defined Functions Page: 8 By Hemant Kumar
Similarly, each rec( ) evaluates its f from the returned value, and finally 6 is returned to main( ). The sequence would be grasped better by following the arrows shown in following Figure Let it be clear that while executing the program there do not exist so many copies of the function rec( ). These have been shown in the figure just to help you keep track of how the control flows during successive recursive calls. Recursion and Stack There are different ways in which data can be organized. For example, if you are to store five numbers then we can store them in five different variables, an array, a linked list, a binary tree, etc. All these different ways of organizing the data are known as data structures. The compiler uses one such data structure called stack for implementing normal as well as recursive function calls. A stack is a Last in First out (LIFO) data structure. This means that the last item to get stored on the stack (often called Push operation) is the first one to get out of it (often called as Pop operation). Now let us see how the stack works in case of the following program. User Defined Functions Page: 9 By Hemant Kumar
In this program before transferring the execution control to the function fun( ) the values of parameters a and b are pushed onto the stack. Following this the address of the statement printf( ) is pushed on the stack and the control is transferred to fun( ). It is necessary to push this address on the stack. In fun( ) the values of a and b that were pushed on the stack are referred as i and j. In fun( ) the local variable sum gets pushed on the stack. When value of sum is returned sum is popped up from the stack. Next the address of the statement where the control should be returned is popped up from the stack. Using this address the control returns to the printf( ) statement in main( ). Before execution of printf( ) begins the two integers that were earlier pushed on the stack are now popped off. User Defined Functions Page: 10 By Hemant Kumar