Scope of a name is the part of the program within which the name can be used. For parameters of a function and automatic variables (local variables) declared at the beginning of a function, the scope is the function boundary. Local variables of the same name and in different functions are unrelated.
The scope of a function or an external variable lasts from the point at which it is declared to the end of the file being compiled. In the previous section, we implemented stack. If we have main in the same function above the definitions of push and pop functions like this:
int main() { ... } int stack[MAX]; int top = 0; void push(int num) { ... } int pop() { ... }
Both push and pop functions can’t be accessed from main. Also, the external variables stack and top are not visible to main.
In cases where an external variable is referred before it is defined, or defined in a different source file, then an extern declaration (as shown below) is mandatory before the variable is referenced in the program.
extern int stack[]; /* Array sizes are optional with extern declaration */ extern int top;
There must be only one definition of an external variable among all the files that make up the source program.
Also, to access functions like push and pop from main in the above snipped, we need to declare it before main like this:
void push(int); int pop(void);