Is it possible to call a function within another function in C/C++?
Yes, it is possible to call a function within another function in C and C++. This is known as nested function calls.
Here's an example of a C++ program that calls a function within another function:
- #include <iostream>
- void print_hello() {
- std::cout << "Hello, World!" << std::endl;
- }
- void print_greeting() {
- std::cout << "Welcome to the program!" << std::endl;
- print_hello(); // function call
- }
- int main() {
- print_greeting();
- return 0;
- }
In this example, the print_hello()
function is called within the print_greeting()
function. The print_greeting()
function first prints a message to the console, and then calls the print_hello()
function which prints a different message.
Functions can be nested as many levels as necessary, but it's important to keep in mind that deeply nested function calls can make the code hard to read and understand. Additionally, excessively deep nesting of function calls can cause a stack overflow if the stack size is too small.
It's also worth noting that when a function is called within another function, the program execution jumps to the called function, performs the operations defined in the called function, and then goes back to the point where it was called, in the order that the function calls were made.
Comments
Post a Comment