In C++, functions can have a limited scope or a broader reach within the program. Functions can be classified into two categories based on where they can be accessed within a program.
- Local Functions
- Global Functions
1. Local Functions
Local functions are those functions that are defined within the body of another function. Typically, we utilize built-in functions within the main()
function to carry out our tasks.
These declarations are referred to as local because they are confined to the scope of the main()
function and cannot be accessed from outside of it.
2. Global Functions
A global function is a function that is defined outside of any other function. It can be accessed from any part of the program. Typically, user-defined functions are considered global functions if they are defined before the main()
function and are thus accessible to every part of the program.
Example: A C++ Program Demonstrating The Local and Global Functions
#include <iostream> // Global function declaration void globalFunction(); using namespace std; int main() { // Calling global function globalFunction(); // Local function declaration and definition void localFunction() { cout << "Inside localFunction" << endl; } // Attempt to access localFunction here (will result in a compilation error) localFunction(); return 0; } // Global function definition void globalFunction() { cout << "Inside globalFunction" << endl; }
Here,
- We have two types of functions: a global function named
globalFunction
and a local function defined within themain()
function.
globalFunction
is declared at the beginning of the program outside of any other function. It’s a global function because it’s not enclosed within another function’s body. Global functions can be accessed from any part of the program.
- Inside the
main()
function, we callglobalFunction()
directly, demonstrating that it can be accessed from within any function.
- After calling
globalFunction()
, we define a local function namedlocalFunction
within themain()
function. This function is only accessible within themain()
function.
- Inside
localFunction
, we print a message to the console. This function is local to themain()
function, meaning it cannot be accessed from outside ofmain()
.
- Finally, we call
localFunction()
withinmain()
to demonstrate its usage.