A C program consists of a set of external objects, either functions or variables. The term “external” is used in contrast to “internal”, which describes the arguments and variables defined inside functions. External variables are defined outside of any function, thus available across multiple functions. Functions are always external, as C does not allow nested functions.
External variables provide an alternative to function arguments and return values for communicating data between functions as they are globally accessible. If a large number of variables must be shared among functions, external variables can be efficient and convenient. However, this may have adverse effect on program structure and lead to too many data connections between functions.
In a situation where two functions must share data but don’t call each other, external variables may prove to be handy.
Let’s look at the following code that implements a stack.
#define MAX 100 int stack[MAX]; int top = 0; void push(int num) { if (top < MAX) stack[top++] = num; else printf("Stack is full!\n"); } int pop() { if (top > 0) return stack[--top]; printf("Stack is empty!\n"); return 0; }
Here, both push and pop functions access the external variables top and stack.