Functions in C

Function is a block of statements which perform some specific task and always return single value to the calling function. Functions in c 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.

Library Functions

A function which is predefined in c language is called library function. printf(), scanf(), getch() etc are examples of built-in or library functions.

User Defined Functions

A function written by a programmer is called user defined function.

User Defined Function Example

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.

Leave a Reply

Your email address will not be published. Required fields are marked *