Tuesday 10 January 2012

Functions in C

In programming, a big task is divided into smaller ones to enable programmers to develop on a solid foundation that others have done instead of starting over from scratch. In order to do so, function is invented in programming world. Proper functions hide its operation details from the external programs using them and expose only the interface and its usage.
Function is a block of statements which perform some specific task and always return single value to the calling function. Functions are used to minimize the repetition of code.
Some languages distinguish between functions which return variables and those which don't. C assumes that every function will return a value. If the programmer wants a return value, this is achieved using the return statement. If no return value is required, none should be used when calling the function.
There are two types of functions in c language.
1. Library Functions
A function which is predefined in c language is called library function printf(), scanf(), getch() etc are library functions
2. User Defined Functions
A function written by a programmer is called user defined function.
Example
#include
int add (int x, int y) {
int z;
z = x + y;
return (z);
}
main ()
{
int i, j, k;
i = 15;
j = 5;
k = add(i, j);
printf ("The value of k is %d\n", k);
}
Output
The value of k is 30
Scope of Function:
Only a limited amount of information is available within the body of each function. Variables declared within the calling function can't be accessed from the outside functions unless they are passed to the called function as arguments.
Global Variables:
A variable that is declared out side all functions is called Global variable. Global variables don't die on return from a function. Their value is retained, and is available to any other function in whole program.
Local Variables:
A variable that is declared within a function is called Local variable. They are created each time the function is called, and destroyed on return from the function. The values passed to the functions (arguments) are also treated like local variables.
Static Variables:
Static variables are like local variables but they don't die on return from the function. Instead their last value is retained, and it becomes available when the function is called again.

No comments:

Post a Comment

host gator coupon