Local and Global Variables in C

programming

Summary: In this tutorial, we will learn what local and global variables are in the C programming language.

What is a Variable?

A variable in C is a named memory location that can store values.

The values can be of any data type supported by the language, such as integer, string, etc.

Example:

int var = 123;

Types of Variables

Variables in C are of two types:

  • Global
  • Local

Local Variable

Local variables in C are those variables that have been declared inside of any scope (i.e. inside {}).

A scope can be a function, loop, block, structure, or anything that has its own body.

Since local variables are declared inside a scope, it is only accessible inside that particular scope only.

Example:

int main(void) {

  /*can access local1
   *cannot access local2 */
  
  int i, local1 = 25;
  printf("%d",local1);

  while(local1 != 0){
    //can access both local1 and local2
    int local2 = 5;
    printf("%d", local2);
    local1 = 0;
  }
  return 0;
}

Output:

25
5

If we try to access local2 outside of the while loop, we will get an error from the compiler.

In conclusion, we can say that the local variable has a limited scope, it cannot be accessed outside of the scope in which it has been declared.

Global Variable

A global variable in C is not bounded by any scope and is usually declared below header file inclusion statements.

It can be accessed anywhere throughout the program and with the use of extern, a global variable can also be accessed in different files.

Example:

#include <stdio.h>

//can be accessed throughout the function
int global = 77;

void print_global(){
  printf("Global variable inside function: %d",global);
}
 
int main(void) {
  print_global();
  printf(" \nGlobal variable inside main: %d",global);
  return 0;
}

Output:

Global variable inside function: 77
Global variable inside main: 77

It is because global variable is declared globally that we are able to use it in print_global as well as in the main method.

Can Local and Global Variable have the Same Name?

Yes, a global and local variable can have the same name but in that case, the variable with the local scope (i.e. local variable) will override the accessibility of the global variable.

This means that the reference to the global variable will be lost where the local variable has the same name as the global variable.

int myVAr = 77;

int main(void) {
  int  myVar = 41;
  printf("Inside main: %d",myVar);
  return 0;
}

Output:

Inside main: 41

Hope you got a little idea about the global and local variables of the C language. Please comment below if you have any doubts or suggestions.

Leave a Reply

Your email address will not be published. Required fields are marked *