A function is a block of logically connected executable statements separated from the rest of the program. It can also be understood as a sub program that works for a specific purpose. Sometimes, a set of statements are to be repeatedly appear in the same program or in another case a code written once is needed in another program. In these cases, a separate function can be defined to keep the required code and use the code wherever we want by invoking the function.
Advantages of defining functions
- improves readability of the main program
- reusability in the same or other programs
C Language is also known as procedure-oriented programming language since every C program looks like a collection of functions. A procedure is also known as a process or sub program or function.
Two types of functions we can see in C Program
- Library or built-in or pre-defined functions Eg: printf, scanf etc
- Functions created based on user requirement are known user-defined functions
Function Calling Mechanism
The function which is calling another function is known as caller function and the function which is being called is known as called function. When a function is called, the control transfers to the called function, which will be executed, and then transfers the control back to the caller function (to the statement following the function call).
The three requirements of every function
- definition – specifaction of what is to be done when the function is invoked. It can be also understood as job or task of the function.
- declaration of the function (optional sometimes) — introduction of the function along with return type and arguments to its caller. It is only necessary when a function is appearing in the code before its definition.
- invocation of the function — asking the function to perform what is specified in its definition.
//Example showing the 3 requirements of function
main() //definition of the main function
{
void func(void); //declaration of function
………………….
func(); //invocation of function
…………….
…………….
……………
func();
…………….
…………….
func();
……………
}
void func(void) //definition of function
{
…………….
…………….
……………
}