Previous | Home | Next |
What is function
A function is a self-contained block of statements that perform a coherent task of some kind.
Example
main( ) { message( ) ; printf ( "\nCry, and you stop the monotony!" ) ; } message( ) { printf ( "\nSmile, and the world smiles with you..." ) ; } The output will be-- Smile, and the world smiles with you... Cry, and you stop the monotony!
In the above program the main() itself is a function. through the main we are calling the function message().that mean the control passes to the function message(). when the message() function runs out of statement to execute, the control returns to the main().thus main() becomes the "calling function" where as the message() becomes the "called function".
Some important points in the the C for functions are given below:
- Any C program contains at least one function.
- If a program contains only one function, it must be main( ).
- If a C program contains more than one function, then one (and only one) of these functions must be main( ), because program execution always begins with main( ).
- There is no limit on the number of functions that might be present in a C program.
- Each function in a program is called in the sequence specified by the function calls in main( ).
- After each function has done its thing, control returns to main( ).When main( ) runs out of function calls, the program ends.
Thus, we can say that-
- A C program is a collection of one or more function.
- A function gets called when the function name is followed by a semicolon. For example:
main( ) { argentina( ) ; }
argentina( ) { statement 1 ; statement 2 ; statement 3 ; }
- Any function can be called from any other function. Even main( ) can be called from other functions. For example-
main( ) { message( ) ; } message( ) { printf ( "\nCan't imagine life without C" ) ; main( ) ; }
main( ) { message( ) ; message( ) ; } message( ) { printf ( "\nJewel Thief!!" ) ; }
Types of functions
There are basically two types of function:
- library function (printf(), scanf())
- user defined function (brazil(), usa())
We can also describe the category of the function under it's type.
A function may belong to any one of the following categories:
- Functions with no arguments and no return values.
- Functions with arguments and no return values.
- Functions with arguments and return values.
- Functions that return multiple values.
- Functions with no arguments and return values.
#include<stdio.h> #include<conio.h> void add(int x,int y) { int result; result = x+y; printf("Sum of %d and %d is %d.\n\n",x,y,result); } void main() { clrscr(); add(10,15); add(55,64); add(168,325); getch(); }
Library functions are nothing but commonly required functions grouped together and stored in what is called a Library.
Previous | Home | Next |