Sunday 19 May 2013

Function in C




FUNCTIONS


A function is a self contained program segment that carries out a specific, well-defined task.

Every c program can be thought of as a collection of these functions. A large problem has to be split into smaller segments so that it can be efficiently solved. This is where, functions come into the picture. They  are actually the smaller segments, which help solve the large problems.

The C language supports two types of functions:

1.  Library Functions
2.  User defined Functions

The library functions are pre-defined set of functions. Their task is limited. A user cannot understand the internal working of these functions. The user can only use the functions but cant change or modify them.

Ex:  sqrt(81) gives result 9. Here the user need not worry about its source code, but the result should be provided by the function.

The User defined functions are totally different. The functions defined by the user according to his  requirement are called as User defined functions. The user can modify the function according to the  requirement. The user certainly understands the internal working of the function. The user has full scope to implement his own ideas in the function. Thus the set of such user defined functions can be useful to another programmer. One should include the file in which the user-defined functions are stored to call the functions in the program.

Ex: Let square(9) is user-defined function which gives the result 81.

Here the user knows the internal working of the square() function, as its source code is visible. This is the major difference between the two types of functions.

Why we use functions?

1.  If we want to perform a task repetitively then it is not necessary to re-write the particular  block  of  the  program  again  and  again.  Shift  the  particular  block  of statements in a user-defined  function. The function definecan be used for any number of times to perform the task.

Suppose a section  of  code in  a program  calculates  the simple  interest  for  some specified amount, time and rate of interest. Consider a scenario, wherein later on in the same program the same calculation has to be done for a different amount, rate and time. Functions come to rescue here.  Rather than writing the same instructions all over again, a function can be written to calculate the simple interest for any specified amount, time and rate. The program control is then transferred to  the  function, the calculations are performed and the control is transferred back to the place from where it was transferred.
2.  Using functions large programs can be reduced to smaller ones.        1



3.  It is easy to debug and find out the errors in it. It also increases readability.
4.  Programs containing functions are also easier to maintain, because modifications, if required, can be confined to certain functions within the program. In addition to this program, functions can be put  in  a library of related functions and used by many programs, thus saving on coding time.
5.  Facilitates top-down modular programming. In this programming style, the high level of the overall program is solved first while the details of each lower level functions are addressed later.

Elements of user-defined functions:

We know that functions are classified as one of the derived data types in C. So, we can define functions and use them like any other variable in C programs. Therefore we can observe the following similarities between the functions and variables in C.

1.  Both function names and variable names are considered as identifiers.
2.  Like variables, functions also have types (data types) associated with them.
3.  Like variables, function names and their types must be declared and defined before they are used in a program.

In order to make use of a user-defined function, we need to establish three elements that are related to functions.

1.  Function definition
2.  Function call
3.  Function declaration

Function definition (Function Implementation):

It  is  an  independent  program  module  that  is  specifically  written  to  implement  the requirements of the function. It includes the following elements:

Function type, function name, list of parameters (arguments), local variable declarations, body of the functions (list of statements), and a return statement.

All the six elements are grouped into two parts, namely,

1.  Function header (First three elements)
2.  Function body (Last  three statements )

The function structure: The general syntax of a function in C is:



type_specifier function_name (arguments)
{
local variable declaration;
statement-1;
statement-2;
.................... return (value);
}

                                                                                                                                                                                                      2



The type_specifier specifies the data type of the value, which the function will return. If no data type is specified, the function is assumed to return an integer result. The arguments are separated by commas. A function is not returning anything; then we need to specify the return type as void. A pair of empty  parentheses  must follow the function name if the function definition does not include any arguments.

The parameters list / arguments list declares the variables that will receive the data sent by the calling program. They serve as input data to the function o carry out the specific task.

Types of parameters:

1. Actual parameters: The arguments of calling functions are called as actual parameters.
2. Formal parameters: The arguments of called functions are called as formal parameters.

Note:
A semicolon is not used at the end of the function header.

The body of the function may consist of one or many statements necessary for performing the required task. The body consist of three parts:

1.  Local variable declaration
2.  Function statements that perform the task of the function
3.  A return statement that returns the value evaluated by the function. If a function is not returning any value then we can omit the return statement.

Function call:
A compiler  executes  the  function  when  a  semi-colon  is  followed  by function  name.  A
function  can  be called  simply by using its  name like other C  statement,  terminated by semicolon.

A function can be called any number of times. A function can be called from other function, but a function cannot be defined in another function. We can call main ( ) function from other functions.
EX: 1. /* program to call main function from another user defined function*/
void main()
{
message();
}
void message ( )
{
printf(\n welcome to C lab);
main();
}
EX:2 /*Program on functions*/
void main ( )
{
printf(\n I am in main);
india ( )
{
printf(\n i am in india);
}     }
Here the above program code would be wrong. Since india ( ) is defined in main ( ) function.

                                                                                                                                                                                                      3



EX:3 /* Program to show how user defined function is called */
void main()
{
int x=1,y=2,z; z=add (x,y); printf(“z=%d,z);
}
add (a,b)
{
return (a+b);
}

In the above program values of x, y (actual parameters) are passed to function add ( ). Formal arguments „a and „b receive the values. The called function add ( ) calculates the addition of both the variables and returns the result. The result is collected by the variable z of main ( ) which is printed through the printf ( ) statement.
Note:
1.  If  the  actual  parameters  are  more  than  the  formal  parameters,  the  extra  actual
arguments will be discarded.
2.  On the other hand, if the actual arguments are less than the formals, the unmatched formal arguments will be initialized to some garbage.
3.  Any match in data types may also result in some garbage values.
4.    The  user-defined  function  can  call  only  those  user-defined  functions  which  are defined before it.

Return values and their types:
The value evaluated by any function is send back to the calling function by using return
statement. The called function can only return only one value per call. The return statement has the following forms:

1.  return;
2.    return(expression);

The first form does not return any value to the calling function; it acts as the closing brace of the function.  When a return is encountered, the control is immediately passed back to the calling function.

A function may have more than one return statement. This situation arises when the value returned is based on certain conditions:
EX: if(a>b) return(1); else return(0);

Note:
1.  All functions by default return integer type data. But, we can force a function to return
a particular type of data by using a type specifier in the function header as discussed earlier.
2.  Absence of return statement in called function indicates that no value is returned to the calling function, such functions are called as void.

                                                                                                                                                                                                      4



How function works?
1.  Once a function is defined and called, it takes some data from the calling function and
returns a value to the called function.
2.  Whenever a function is called, control passes to the called function and working of the calling function  is stopped. When the execution of the called function is completed, control returns back to the calling function and execute the next statement.
3.  The values of actual arguments passed by the calling function are received by the formal arguments of the called function. The number of actual and formal arguments should be the same.
Extra arguments are discarded if they are defined. If the formal arguments are more than the actual arguments then the extra arguments appear as garbage. Any mismatch in data type will produce the unexpected result.
4.  The function operates on formal arguments and sends back the result to the calling function. The return ( ) statement performs this task.

Characteristics of functions:

Depending upon the arguments present, return value send the result back to the calling function. Based on this, the functions are divided into 4 types:
1.  Without arguments and return values.
2.  Without arguments and but with return values.
3.  With arguments but without return values.
4.  With arguments and return values.

Without arguments and return values
Calling function
Analysis
Called function
main()
{
................
................ add ( );
................
................
}





ßNo arguments are passed.

No values are sent back à

add ( )
{
............
............
............
............
}

1.  In this type neither the data is passed through the calling function nor is the data sent back from the called function.
2.  There is no data transfer between calling function and called function.
3.  If the functions are used to perform any operations, they act independently. They read data values and print result in the same block.
4.  This type of functions may be useful to print some messages, draw a line or split the line etc.
Ex: /* program to display message using user-defined function*/
void main ( )
{
void message ( );             /*FUNCTION PROTOTYPE*/
message ( );                    /*FUNCTION CALL*/
}
void message ( )             /*FUNCTION DEFINITION*/
{
printf(“Have a nice day”);    }

0 comments:

Post a Comment