A function is a self-contained block of statement that performs a coherent task of some kind. Every 'C program can be thought of as a collection of differnet functions.
Functions break large computing tasks into smaller ones. They help in modular development of programs. They save programming effort because the same function can be called from different parts of the program (this may be termed as sharing of code). C has been designed to make functions efficient and easy to use.
There are basically two types of functions in C:
• Library functions
• User defined functions
Library functions are prewritten and precompiled by the compiler vendor and comes along with the compiler software as a library of functions. When you are buying the compiler software you are buying the library also.
In the previous chapters we have used several library functions like printf, scant, sqrt and many more. In this chapter we will learn how to create our own functions.
There are three steps involved in creating and using a user defined function.
• Declaring a function prototype
• Defining the function
• Calling the function
In function prototype declaration we specify the name of the function, its return type and the list of argument types in the order in which it is used in the function.
Function name is a user defined name just like any other C variable name. It will be advantageous and it is strongly recommended that the function name should reflect the nature of the task it is performing, like write(), read() etc function names.
In function definition, we write the actual lines of code required to accomplish the task assigned to the function. Function call is the statement you use in your programs to invoke the services of the function.
So far we have used only library functions like printf(), scanf(), getchar() etc in our example programs. You have also seen how library function calls are made from a program. We haven't done any user defined functions so far. The following example program will illustrate how to declare, define and call a user-defined function in a C program.
You will find that a user-defined function is called in the same way we call a library function.
Example:
/Tine 1*/ nine 2*1 /"line 3*/ nine 4*/ nine 5*/ Dine 6*/ nine 7*1 nine 8*/ nine 9*/ nine 10*/ nine 11*/ /*line 12*/ /*line 13*/
#include
welcome()
{
printf("You are welcome!");
)
main
{
printf("Hello!\n");
welcome();
printf("Have a nice day!"); }
Output:
Hello!
You are welcome!
Have a nice day!
This example illustrates the use of a simple user-defined function. The user-defined function welcome() is defined from line 3 though line 6. In line 3 the function name is declared. The pair of empty parentheses following the function name welcome indicates that the function does not accept any parameters. This function simply prints the string "You are welcome!". The program execution as usual starts from the main function. The string "Hello!" is first printed. Next the main function calls the function welcome. Now let us understand what we actually mean by calling a function. By calling function welcome we mean that the control passes to the function segment welcome starting at line 3. The execution of function main is temporarily suspended, and function welcome is executed. When the function has completed its execution, the control returns to function main, which begins executing its code at the exact point where it left off i.e from line 12 onwords. Thus the function main is referred to as the calling function while the function welcome is referred to as the called function.
Format of a Function
return-type name (argument list if any) argument declarations, if any
{
[declarations] [statements]
}
The first line of a function definition specifies the type of value returned by the function, followed by the function name and an optional set of arguments, separated by commas and enclosed in parentheses.
This type specification, however, can be omitted if the function returns an integer value, since a C function is assumed to return an integer value, by
default. In this context, it should also be noted that a function can return only a single value per call.
The type specification is followed by the function name. The rules for constructing variable names apply to function names also.
The function name is followed by an optional list of arguments. These arguments allow information to be transferred from the calling portion of the program to the function. They are known as the formal arguments or forma parameters or simply parameters. The corresponding parameters in the function call are called actual arguments, since they define the information actually being transferred. The actual arguments are also called actual parameters or simply arguments. The values of the actual arguments are assigned to the formal arguments on a one to one basis, starting with the first argument. Thus the values of the actual arguments become the values of the formal arguments inside the called function. In this context it should be noted that the identifiers used as formal arguments are local in the sense that they are not recognized outside the function. Hence, the names of the formal arguments may be the same as the names of other identifiers that appeal; outside the function definition.
The argument declarations follow the first line. All formal arguments must be declared at this point in the function. Each formal argument must have the same data type as the corresponding actual argument, that is, each forma argument must be of the same data type it receives from the calling portion of the program.
The remainder of the function is a compound statement that defines the action to be taken by the function. This compound statement is also referred to as the body of the function.
As we have seen a function may or may not send back any value to the calling function. If it does, it is done through the return statement. While it is possible to pass any number of values to the called function, the called function can return only a single value per call, at the most.
The return statement can take one of the following forms
return; or
return(expression);
The first form of return does not return any value; it simply causes the contralto revert back the calling portion of the program, without any information transfer. The second form of return returns the value of the expression.
Example:
A minimal function is
dummy()
{ }
which does nothing.
Example:
#include
{
int i; for(i=1;i<=10;i++)
printf("\n Square of %d is %d",i,square(i)); }
square(int x)
{
intj;
j = x*x;
return();
}
This example illustrates a function, which computes the square of an integer. Here x is the formal argument while i is the actual argument. Also, note that the square function can also be written as
square(intx)
{
return(x*x);
}
Further, notice that the function square has been defined after it has been accessed. This does not pose any problem, since the function square returns an integer value. However, if a function returns a non-integer quantity and the portion of the program containing the function call precedes the function definition, then there must be a function declaration in the calling portion of the program. This is referred to as forward declaration or function prototype declaration. This function declaration effectively informs the compiler that a function or function prototype declaration, will be accessed before it is defined. In its simplest form, a function declaration can be written as
return-type name();
where return-type refers to the data type of the quantity returned by the function and name refers to the function name.
Example:
#include
{
int num, den;
float todecimal();
printffEnter numerator:");
scanf("%d", num);
printf("Enter denominator:");
scanf("%d", den);
printf(“The fraction when converted to decimal form becomes
%f\n", todecimal(num,den));
}
float todecimal(int num, int den)
{
float res;
res=(float)num/den;
retum(res);
}
In this example, the function todecimal returns a float value and is defined after it is accessed in function main. Thus there is a forward declaration inside the function main. Also notice that in this example, both the formal and actual arguments have the same names.
Example:
type (c) /* return type of ASCII character */
int c;
{ if ( c>= 'A' && c <= T)
{ printf ("c is a LETTER \n");
return (c);
} else
if ( c>= '0' && c <= '9')
{ printf("c is a DIGIT \n"); return (c);
} else return (c);
This function returns the ASCII character passed on to it. It also gives a message if the character is a letter or a digit. Notice the multiple return statements in this function, but note that only single return statement is executed per call and a single value is returned per call.
Passing Arguments to a Function
By now we are already familiar with how to call functions. However, we should note that, whenever we have called a function and passed something to it, we have always passed the values of the variables to it, that is, the value of the actual argument is copied into the function. Thus, the value of the corresponding formal argument can be altered within the function, but the value of the actual argument within the calling function will not change. This procedure for passing the value of an argument to a function is known as passing by value and such function calls are known as call by value.
Example:
#include
main()
{
int n=1;
printf(“n = %d in main, before calling increments",n);
increment(n);
printf("n = %d in main, after calling increment\n",n);
}
increment(n) int n;
{
n++;
printf("n = %d in increment, after changing and before returning");
return;
}
Output:
n = 1 in main, before calling increment
n = 2 in increment, after changing and before returning
n = 1 in main, after calling increment
The original value of n, that is 1, is displayed when main begins execution. This value is than passed to the function increment, where it is incremented by 1 and the new value is displayed. Note that it is the altered value of the formal argument that is displayed within the function increment. Finally, the value of the actual argument n within main is again displayed, after the control is transferred back to main from increment. The results show that n is not altered within main, even though the corresponding value of n is changed within the function increment.
Passing an argument by value has its advantages and disadvantages. The advantage is that it protects the value of the actual variable from alterations within the function. The disadvantage is that it prevents information from being transferred back to the calling portion of the program via arguments. Thus passing by value is restricted to a one-way transfer of information and hence restricts the calling function to return only a single value to the called function (via the return statement).
Two-way transfer of information via arguments is possible by a special type of function call, known as call by reference. In this case, instead of passing the value of the variable, the location of the variable (also called the address of the variable) is passed. We will learn about this details in the Chapter on Pointers.
Passing Arrays to a Function
Note: This section uses the concept of arrays, which will be explained in detail in the chapter on arrays later. However because passing arrays to a function is
a very important concept in C we include this section here for the sake of completeness. Also certain concepts like location of the first element of the array used here will become clear to you when we take up pointers in a later chapter. For now you just try to grasp as much as you can from the example given. The concepts given here will be clearer after you understand arrays and pointers in C.
An entire array can be passed to a function. However, the manner in which an array is passed differs markedly from that of an ordinary variable. To pass an array to a function, the array name must appear by itself, without brackets or subscripts, as an actual argument within the function call. The corresponding formal argument is written in the same manner, though it must be declared as an array within the formal argument declarations. When declaring a one-dimensional array as a formal argument, the array name is followed by a pair of empty square brackets. The size of the argument is not specified within the formal argument declaration. In general, in case of a multidimensional array, the first dimension is not specified and simply contains a pair of empty square brackets, but the subsequent dimensions must be specified within square brackets.
In this context it should be noted that arrays are passed differently than single-valued entities. If an array name is specified as an actual argument, the individual array elements are not copied to the function. Instead, the location of the array i.e. the location of the first element is passed to the function. Thus any alteration to an array element within the function will carry over to the calling routine.
Also, note that, an entire array can be passed as an argument, however an entire array cannot be returned via a return statement.
Example:
#include
main()
{
intn[3]={0,1,2}; int i;
printf("\nn in main, before calling increment:\t"); for (i=0; i<3; i++)
printf("%d\t",n[i]);
printf("\n"); increment(n);
printf("\nn in main, after calling increment:\t"); for (i=0; i<3; i++)
printf("%d\t",n[i]);
printf("\n");
}
increment(x) int x();
{
int i;
for(i=0;i<3;i++)
x[i]++; return;
} Output:
n in main, before calling increment: 0 12
n in main, after calling increment: 12 3
Within main we see a call to the function increment. Notice that the array name n appears as an ordinary variable within the function call. In the first line of the function definition, we see the formal argument x. The formal argument declarations establish x as a one-dimensional, integer array. Note that the size of x is not specified within the formal argument declaration. Also notice that the value of the elements changes after call to increment is made.
Example :
#include
main()
{
int n[3][4];
increment(n);
}
increment(x) intx() [4]; {
}
Notice that multidimensional arrays are passed in the same manner as one-dimensional arrays, except that the formal argument declarations within the function definition must include explicit size specifications in all of the subscript positions but the first. These size specifications must be consistent with the corresponding size specifications in the calling program. The first subscript position may be written as an empty pair of square brackets, as with a one-dimensional array.
C Storage Classes
In addition to having a data type (int, float etc), every variable in C program also belongs to a storage class.
Storage class refers to the permanence or longevity of a variable and its scope within the program, that is the part of the program over which the variable is recognized.
We have not mentioned storage classes yet, though we have written several programs in C. We were able to get away with this because storage classes have defaults. If we don't specify a storage class of a variable in its declaration, the compiler will assume a storage class depending on the context in which the variable is used.
C supports the following storage classes -
automatic (local) extern (global) static register
The general syntax for declaring a variable is thus
storage-class data-type variable_name
Automatic Variables
Automatic variables are always declared within a function and are local to the function in which they are defined, that is, their scope is confined to that function. Because of this property, automatic variables are also referred to as local or internal variables. Automatic variables defined in different functions thus be independent of one another, even if they have the same name.
Any variable declared within a function is interpreted as an automatic variable unless a different storage-class specification is included within the declaration. This includes formal argument declarations also. All the variables in the examples encountered until now in this book have been automatic variables. We may also use the keyword auto to declare automatic variables explicitly.
main() {
auto int n;
} '
Advantage of using local variables is that the memory is not occupied permanently. The following example illustrates the use of local or automatic variable.
Example :
main()
{
int i = 0;
divert();
printff%d\n",i);
divert();
printf("%d\n",i);
}
divert();
int i = 0;
i+=2;
printf("%d\n",i);
}
Output:
2 à Output of printf() inside function divert() .
Value of i is changed to 2 and printed.
0 à Output of first printf() inside main().
2à Output of second call to divert() from main().
0à Output of second printf() in main()
The scope of an automatic variable can be smaller than an entire function. In fact, automatic variables can be declared within a single compound statement.
Example:
main()
{ int i = 0;
{
inti=1;
{
int i=2; printf("%d\n",i);
} printf("%d\n",i);
} printf("%d\n",i);
Output: 2,1,0
Note that the compiler treats the three is as totally different variables, since they are defined in different blocks. Once the control comes out of the innermost block, the variable i with value 2 is lost, and hence i in the second printf refers to i with value 1. Similarly, when the control comes out of the next innermost block, the third printf refers to i with value 0.
It should also be noted that if an automatic variable is not initialized in some manner, it will contain an unpredictable value, which is often called a garbage value.
Extern Storage Class
The extern storage class does not create a variable, but merely informs the compiler of its existence. Their scope extends from the point of definition through the remainder of the program. External variables differ from the variables we have dealt with so far in that their scope is global and not local They are declared outside all functions (hence called global) and are available to all functions that want to use them. Hence they usually span two or more functions and often an entire program. If a variable is declared globally, it can be referenced by any function in the same program file. If it is declared in the middle of the program and if a function above the declaration statement references it, that function must declare the variable to be extern. The program below shows this point.
Example :
Main()
{
extern int i;
printf("i=%d\n",l);
}
int i = 5;
Output:
This program will print
i=5
since the i referred to in main is the global variable i, no local i is declared. Also, in this context note that, unlike local variables, global variables are automatically initialized to 0. Moreover, if a local and an external variable have the same name, the local variable takes precedence over the external variable, though the value of the external variable remains unaffected by the manipulation of the local variable.
Example:
main()
extern int i; int i=2;
printf("i=%d\n",i);
}
int i = 5;
Output:
This program will print i=2
Here the local variable gets precedence over the external variable.
An extern declaration may never include an initialization, since the variable is not created when it is declared as extern.
Since an extern declaration is not needed when a global variable is used after it is declared, most programmers place all global declarations at the beginning of the program above the main() function and dispense with the extern declaration. Even if an extern declaration is not necessary, it can still be useful as documentation. If a function contains declarations for all global variables used in the function, a reader can see all variables used by the program merely by examining the declaration section at the beginning of the function.
When a global extern declaration is made (outside a function), it indicates that the variable referred to is declared in another file (a file is a place on the disk where a group of related data is stored, in our case a file contains a program in C), which will be linked with the file containing the extern declaration. For example, the global declaration
extern int ram;
means that:
1. Within this program file, ram is a global variable
2. The actual storage for ram is allocated in another program file and in that file ram is also global.
In other words, global extern declarations facilitate communication between files of a multi-file program.
Format:
extern datatype variablename;
So, diagrammatically, the above can be represented as follows:
int global,
main()
{
extern int global; function(arg; int arg;
int local;
/* statements here can
access local and
global 7 }
{
int local_of_funcn; /* statements here can access arg, global, and local of funcn*/ }
Saved as main.c
On a Unix machine, the above program, which is kept in two files, can be compiled using the following command:
cc -o mine main.c func.c
Static Variables
Static variables are local to a particular function but their values are retained across function calls. They remain in existence throughout the life of the program rather than coming and going each time the function is activated.
Example:
Main ()
{
Int i = 0; divert ();
printf("The value of i in main after the function call is %d\n",i);
divert();
printf("The value of i in main after the function call is %d\n",i);
)
Diverts ()
{
static int i = 0;
i+=2;
Printf ("The static value of i in the function is %d\n",i);}
Outputs:
The static value of i in the function is 2
The value of i in main after the function call is 0
The static value of i in the function is 4
The value of i in main after the function call is 0
Here the static variable i retains its value from the first function call to the second.
Note:
A static variable is initialized only once, when the program is compiled. It is never initialized again. Like external variables, if no explicit initialization statement is given, a static variable is automatically initialized to 0.
Register Variables
The compiler can be told to keep a variable in one of the machine's registers, instead of the memory (where normal variables are stored). Since a register access is much faster than a memory access, keeping the frequently accessed variables like loop control variables in the register, will lead to faster execution of programs. This is shown in the example below.
Example:
Main()
register int i; for (i=i; i<=10; i++) printf ("\n%d",i); }
Since only a few variables can be placed in the registers, it is important to carefully select the variables for this purpose. However, C will automatically convert register variables into non-register automatic variables once the limit is reached. Moreover, most compilers allow only int and char variables to be placed in the register. However, if any other variable type is used with the register, the compiler will not generate any error message, it simply treats the variables to be of auto storage class.
Recursive Functions
A recursive function is one that calls itself. A function calling itself must halt ultimately at some definite point to avoid infinite looping. This concept can be explained with reference to the factorial function in mathematics. Given a positive number n, the factorial of that number can be defined as:
1! = 1
'2! = 2* (2-1)
n! = (n)*((n-1)!)
which in turn means
n! = (n)*(n-ir(n-2)....
Suppose we want to find the factorial of 6. Note the second line in the first formula makes reference to itself, which is what we mean by recursion. Therefore 6! = (6)*(5!)
But 5! Is equal to (5)*(4!) so 6! Is equal to
(6)*(5)*(4!)
If this process is continued, we end up with
6! = (6r(5r(4r(3r(2)*(1!)*(0!)
Since 0! Is equal to 1, 6! Is equal to (6)(5)(4)(3)(2)(1), which is equal to 720.
In C a recursive function that calculates a factorial can be written as follows: factorial (n) int n;
{
If (n==1)
Retum (1); else
return (n * factorial(n-l));
}
Local variables in C are auto by default. Therefore, when a function calls itself, a new set of local variables is created (except for those variables declared as static). The variable names are the same as those in the calling function, but the memory locations associated with them are different.
Salient Features of Functions
• Function definitions can occur anywhere in a C program, but not inside another function definition.
• A program is just a set of individual function definitions.
• Communication between functions is through -
• arguments
• values returned by functions
• global variables
• Any function can call any other function, including itself, i.e. recursion is allowed.
• A function is called by just specifying its name, followed by the arguments (if any) to be passed to it. The arguments are separated by commas and enclosed in round brackets ().
• The return statement is the mechanism for returning a value from the called function to its caller.
Any expression can be used in the return statement . The format of the return statement is:
return (expression);
Note:
• The calling function is free to ignore the return value if it wishes.
• A function may not return any value i.e., it may or may not contain the return statement. By default, if the function has executed successfully, it returns a value of TRUE i.e. 1 and FALSE or 0 if there was an error.
• Whenever a function is called in an expression, the value returned by the function is used in the expression.
Example:
Power (x,n) /* n > o 7 intx, n;
{
int i,p;
P = 1;
for (i = 1; i <= n; ++i) p = p*x; return (p);
} This function can be called by any of the following ways:
printf ("%d %d \n", power (2,2), power (-3,2));
or
x = n * power (x,n);
or
switch (power (x,y))
{
case 0:...........
case 2:...........
}
Example:
Given an array of sorted list of integers, this function called binary search, searches for a particular item in the list. In binary search, the target value is compared with the array's middle element. Since the array is sorted, if the required value is smaller, we know that all values greater than the middle element can be ignored. That is, in one attempt, we eliminate one half of the list. This search can be applied recursively till the target value is found.
#include
void binary(int, int[], int);
void main()
{
int i;
int num[10];
/* creates a sorted array of 10 integers 7
for(i=0; i<10; i++) num[i];
/* search for 25 in the sorted array 7
binary(25, num,10); }
void binary(int x, int vfj, int n)]
{
int low, high, mid;
low=0;
high=n-1;
while (low <= high)
{
mid = (low + high)/2;
if (x < v[mid])
high = mid -1; else if (x > v[mid])
low = mid + 1; else
{
printf("A match is found\n"); return;
}
}
printf(“Match is not found\n");
}
We have already used the #define statement for defining symbolic constants. They can also be used to define expressions, complete statements or group of statements.
Example:
To define a macro for computing the cube of a given number x and use it to print the cube of first 10 natural numbers.
Example:
# define cube (X) X * X * X
main()
{
int count;
for (count = 1; count <= 10; ++count)
printf ("count = %d cube =%d\n", count. Cube (count));
}
During compilation, each occurrence of cube(x) is replaced by its definition x*x*x, whatever be x.
i.e. cube (count) becomes count*count*count
This is convenient for 2 reasons:
• The actual expression needs to be written only once assigning it a meaningful name, for example,we can now use cube (3.1459) instead of 3.1459* 3.1459* 3.1459.
• Since the macro preprocessor substitutes the name of the macro with its definition during compilation itself, the use of a macro in place of a function eliminates the time delays and other overheads associated with function calls.
However, macros have several disadvantages as well:
• Since macro substitution takes place wherever a reference to a macro appears within a program, a program that contains several references to the same macro may become unreasonably long.
• When passing arguments to a macro, the number of arguments will be checked, but their data types will not. Thus, there is less error checking than with a function call.