In my last tutorial I gave an overview to the functions in C programming. Today I will tell you about the multiple calls within one function and its nuances. So without wasting any time lets head over to a program.
Functions in C Programming
#include<stdio.h> void firstfu(); void secondfu(); void thirdfu(); void fourthfu(); void main() { printf(" Control is in mainn"); firstfu(); } void firstfu() { printf(" Now the control is in firstfu functionn"); thirdfu(); } void secondfu() { printf(" Now the control is in secondfu functionn"); fourthfu(); } void thirdfu() { printf(" Now the control is in thirdfu function n"); secondfu(); } void fourthfu() { printf(" Now the control is in fourthfu function n"); }
Output
A simple concept to learn
Suppose main() function calls another function msg(). When the control reach to the msg() function then the activity of main() will be suspended temporarily. After executing all the statements from the msg() function, the control will automatically goes to the original calling function (main() in our case).
Explanation
- The program starts with main() function and it will print the message inside it. After that I have called the firstfu() function from main(). Remember here main() is calling function and firstfu() is called function.
- Now the control reaches to firstfu() function and the activity of main() function is suspended temporarily. Inside firstfu() function, printf() will print a message. Now I have called thirdfu() function. Remember here firstfu() is calling function and thirdfu() is called function
- Now the control reaches to the thirdfu() function and the activity of firstfu() function is suspended temporarily. And it will execute its printf() function. Now I have called the secondfu() function.
- Same thing will happened to the secondfu() function and it will call the fourthfu() function.
- Now the printf() statement will be executed inside the fourthfu() function. As there is no further call to other function there. So the control will goes back to the calling function. Calling function of fourthfu() is secondfu().
- No more statements is left in secondfu(). So the control will reach to the calling function. thirdfu() is the calling function of secondf().
- Same execution will be done for all of them. And the control will reach to the main() function again. Now no statement is left in main() function, so the program will be terminated.
Points to Remember
1. Any C program contains at least one function and it should be main().
void main()
{
msg();
}
5. We can call one function any number of times.
void main()
{
msg();
msg();
}
6. A function can also called by itself. Such an execution is called recursion.
7. We cannot define one function inside another. We can only call one function from another.