It would not be wrong to say that C language is a function-based language. The C Standard Library contains a large number of predefined functions which may be called in programs for carrying out various processes. Related functions are grouped together under various header files.
We have used several functions of C standard library. Besides, the C language also allows a programmer to define his/her own functions in which case these are known as user-defined functions. In general, the purpose of a function is to receive data and process it; may or may not return a value to the function which has called it. In any program in C there is only one main function in which other functions are called. A function cannot be defined inside another function, it can only be called. Therefore, functions are defined in file scope, i.e., outside the main function, either above the main function or below the main function. In case it is defined below the main, a declaration of the function is placed above the main function. Thus, a function is an independent program module. However, there may be data sharing relationship between the functions. Therefore, if a function is called by a main function, it also supplies data values which become arguments of the called function. The called function may also have its own local data and may return a value to the calling function. A return type function returns only one value. A function is a derived type because its type is derived from the type of data it returns. The other derived types are arrays, pointers, enumerated type, structure, and unions.
Basic types: _Bool, char, int, long, float, double, long double, _Complex, etc.
Derived types: Functions, arrays, pointers, enumeration type, structure type, and union type
Many of us, particularly those with a mathematical background, carry a perception that a function is a formula type mathematical entity whose numerical value has to be found if parameters are given.
However, in the real world, there are many other types of actions which may also be defined and treated as functions in C language programs. Thus, a function in a broader sense may be considered to be a portion of program or a subroutine which may be called in the main program to carry out some actions. This also includes mathematical functions and sub-routines. Thus, functions give us the facility to divide a large program into suitable small segments or modules and each segment may be treated and defined as a function. Because functions are independent entities, these may be tested and verified independently of the main program. Therefore, division of a very large program into suitable functions not only makes the development process easier but also makes the program easier to write and debug. Besides, it allows engaging a number of programming teams in the program development process. The different functions/program segments may be developed separately by different programmers. In the main program, we simply include the header files containing the functions and in main () these functions may simply be called with the required arguments. Remember that a program can have only one main () function. Different data variables that are used in the function definition are its parameters. The actual values of these parameters that are passed on to the function when it is called are known as arguments of the function. The function which calls another function is known as calling function, while the function that is called is known as called function.
Like fundamental types, functions also have types; the function type is known as derived type. If a function returns a value to the calling function it is known as return type function. The type of a return type function is same as the type of data it returns. If a function does not return a value to the calling function we call it a void function. The void function may process data of different types. Similarly, there are functions which are not void and still have no arguments to act upon. These are called functions with void arguments.
In a program, a function is defined only once. However, it may be called as many times as desired. If a function is already defined in C standard library, it should better be used rather than defining another similar function.
There are many advantages in using functions in a program they are:
1. It facilitates top down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower level functions is addressed later.
2. The length of the source program can be reduced by using functions at appropriate places. This factor is critical with microcomputers where memory space is limited.
3. It is easy to locate and isolate a faulty function for further investigation.
4. A function may be used by many other programs this means that a c programmer can build on what others have already done, instead of starting over from scratch.
5. A program can be used to avoid rewriting the same sequence of code at two or more locations in a program. This is especially useful if the code involved is long or complicated.
6. Programming teams does a large percentage of programming. If the program is divided into subprograms, each subprogram can be written by one or two team members of the team rather than having the whole team to work on the complex program
We already know that C support the use of library functions and use defined functions. The library functions are used to carry out a number of commonly used operations or calculations. The user-defined functions are written by the programmer to carry out various individual tasks.
Functions are used in c for the following reasons:
1. Many programs require that a specific function is repeated many times instead of writing the function code as many timers as it is required we can write it as a single function and access the same function again and again as many times as it is required.
2. We can avoid writing redundant program code of some instructions again and again.
3. Programs with using functions are compact & easy to understand.
4. Testing and correcting errors is easy because errors are localized and corrected.
5. We can understand the flow of program, and its code easily since the readability is enhanced while using the functions.
6. A single function written in a program can also be used in other programs also.
Function definition:
[data type] function name (argument list) argument declaration; { local variable declarations; statements; [return expression] }
Types of functions:
A function may belong to any one of the following categories:
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
Functions with no arguments and no return values:
Let us consider the following program
/* Program to illustrate a function with no argument and no return values*/ #include<stdio.h> void statement1(); void statement2(); void starline(); int main() { statement1(); starline(); statement2(); starline(); return 0; } /*function to print a message*/ void statement1() { printf("\n Sample subprogram output"); } void statement2() { printf("\n Sample subprogram output two"); } void starline() { int a; for (a=1;a<40;a++) printf("%c",'*'); printf("\n"); }
In the above example there is no data transfer between the calling function and the called function. When a function has no arguments it does not receive any data from the calling function. Similarly when it does not return value the calling function does not receive any data from the called function. A function that does not return any value cannot be used in an expression it can be used only as independent statement.
Functions with arguments but no return values:
The nature of data communication between the calling function and the arguments to the called function and the called function does not return any values to the calling function this shown in example below:
Consider the following:
Function calls containing appropriate arguments. For example the function call value (500,0.12,5)
Would send the values 500,0.12 and 5 to the function value (p, r, n) and assign values 500 to p, 0.12 to r and 5 to n. the values 500,0.12 and 5 are the actual arguments which become the values of the formal arguments inside the called function.
Both the arguments actual and formal should match in number type and order. The values of actual arguments are assigned to formal arguments on a one to one basis starting with the first argument as shown below:
main() { function1(a1,a2,a3……an) } function1(f1,f2,f3….fn); { function body; }
here a1,a2,a3 are actual arguments and f1,f2,f3 are formal arguments.
The no of formal arguments and actual arguments must be matching to each other suppose if actual arguments are more than the formal arguments, the extra actual arguments are discarded. If the number of actual arguments are less than the formal arguments then the unmatched formal arguments are initialized to some garbage values. In both cases no error message will be generated.
The formal arguments may be valid variable names, the actual arguments may be variable names expressions or constants. The values used in actual arguments must be assigned values before the function call is made.
When a function call is made only a copy of the values actual arguments is passed to the called function. What occurs inside the functions will have no effect on the variables used in the actual argument list.
Let us consider the following program
/*Program to find the largest of two numbers using function*/ #include <stdio.h> void largest(int,int); void main() { int a,b; printf("Enter the two numbers"); scanf("%d%d",&a,&b); largest(a,b); } /*Function to find the largest of two numbers*/ void largest(int a, int b) { if(a>b) printf("Largest element=%d",a); else printf("Largest element=%d",b); }
In the above program we could make the calling function to read the data from the terminal and pass it on to the called function. But function foes not return any value.
Functions with arguments and return values:
The function of the type Arguments with return values will send arguments from the calling function to the called function and expects the result to be returned back from the called function back to the calling function.
To assure a high degree of portability between programs a function should generally be coded without involving any input output operations. For example different programs may require different output formats for displaying the results. Theses shortcomings can be overcome by handing over the result of a function to its calling function where the returned value can be used as required by the program. In the above type of function the following steps are carried out:
1. The function call transfers the controls along with copies of the values of the actual arguments of the particular function where the formal arguments are creates and assigned memory space and are given the values of the actual arguments.
2. The called function is executed line by line in normal fashion until the return statement is encountered. The return value is passed back to the function call is called function.
3. The calling statement is executed normally and return value is thus assigned to the calling function.
Note that the value return by any function when no format is specified is an integer.
Return value data type of function:
A, C function returns a value of type int as the default data type when no other type is specified explicitly. For example if function does all the calculations by using float values and if the return statement such as return (sum); returns only the integer part of the sum. This is since we have not specified any return type for the sum. There is the necessity in some cases it is important to receive float or character or double data type. To enable a calling function to receive a non-integer value from a called function we can do the two things:
1. The explicit type specifier corresponding to the data type required must be mentioned in the function header. The general form of the function definition is
Type_specifier function_name(argument list) Argument declaration; { function statement; }
The type specifier tells the compiler, the type of data the function is to return.
2. The called function must be declared at the start of the body in the calling function, like any other variable. This is to tell the calling function the type of data the function is actually returning. The program given below illustrates the transfer of a floating-point value between functions done in a multiple function program.
#include<stdio.h> void main() { float x,y,add(); double sub(); clrscr(); x = 12.345; y = 9.82; printf("The Addition of a and b is : %f\n" ,add(x,y)); printf("The Subtraction of a and b is : %lf\n",sub(x,y)); } float add(a,b) float a,b; { return(a+b); } double sub(p,q) double p,q; { return(p-q); }
We can notice that the functions too are declared along with the variables. These declarations clarify to the compiler that the return type of the function add is float and sub is double.