Function scope and File scope in C++
The scope for a function or a variable is determined by the place, where it is declared. If it is defined within the body of a function then the scope is local to the function or function scope. For example: if a function named sub() is defined inside another function named super(), then sub() can be accessed only through super(). Hence scope of sub() is local to super().
super()
{
———-
———-
sub()
{
———-
———-
}
}
Here sub() is a local function to super() and is not externally accessible.
If the above declaration of sub() function appears outside super() or all other functions, then it becomes available to all the functions in the file and the scope now is referred to as the file scope. Thus it is accessible from anywhere in the program. Such variables and functions which are globally available within a program are global variables and functions. Hence
super()
{
————-
————-
}
sub()
{
————–
————–
}
Here sub() function is globally available within the program from the point of its definition.
The program demonstrating function scope and file scope is as follows:
#include <iostream.h>
#include <conio.h>
void super(void)
{
cout<<”Inside super…!”;
void sub(void)
{
cout<<”Inside sub…!”;
}
cout<<”Calling sub…!”;
sub(); // sub() function accessible
//as local to the block.
}
void main()
{
cout<<”Calling Super…!”;
super(); //function invoked as defined as a
//global function and has file scope.
cout<<”Calling Sub…!”;
sub(); // sub() function not accessible as
//it is local to the function super() and
//has function scope, thus the
//function is not accessible.
getch();
}