What is a global variable?

A variable declared outside of a function is known as a global variable.

  • The scope of the global variable is throughout the program, i.e. all the functions that are declared in multiple files can access it.
  • The lifetime of a global variable is throughout the program, i.e. memory to the global variables will be allocated when the Execution of the program is started and will become invalid after finishing the Execution of the program.

When a program starts its execution, storage gets allocated to the global variables in the “.data” section and will get de-allocated when the program finishes its execution.

For example, the below global variable (a = 10) can be accessed from both main( ) and fun( ) functions.

#include <stdio.h>

// global variable
int a = 10;

void main()
{
    printf("Priniting in main %d", a);
}

void fun()
{
    printf("printing in fun %d", a);
}

Example #1

The scope of the global variable also starts from the point where we declare it.

In the below example, we are declaring the Global variable after we are using it in the “main” function. Hence we get the undeclared variable error.

#include <stdio.h>
int main()
{
    printf("%d", value);
    return 0;
}
int value = 10;

Example #2

Re-definition of Global variables is not allowed.

In the below example, we are trying to redefine the Global variable with value = 20, it is not allowed in C, so we get a re-definition error.

Remember, re-declaration or re-definition is strictly prohibited in C. If you do so, you will face a compilation error.

#include <stdio.h>
int value = 10;
value = 20;
int main()
{
    printf("%d", value);
    return 0;
}

Example #3

We cannot directly assign one “Global variable” to another “Global variable” outside the function.

In the below example, I am trying to initialize one global variable with another Global variable. Hence we get a compilation error.

Remember, always global variables must be initialized with constants.

#include <stdio.h>
int value = 10;
int value2 = value;
int main()
{
    printf("%d", value);
    return 0;
}

Categorized in:

Tagged in: