Master da Web
Back to Blog

Global and local variables – C/C++ Language

LucasSeptember 1, 20111 min readUpdated on November 4, 2023
Global and local variables – C/C++ Language

Global variables are variables declared outside a function, unlike local variables which are declared inside a function.


#include  

int a = 1; // GLOBAL VARIABLE

void main()
{
  int b = 2; // LOCAL VARIABLE

  printf("Value of variable 'a': %d", a);
  printf("\nValue of variable 'b': %d", b);
}

When a variable is declared within a function, it can only be used within that function, in the example above the variable ‘a’ can only be used within the MAIN function, otherwise it will be given as non-existent. Global ones, as the name implies, can be used throughout the program.

Despite some of the facilities that global variables bring us, they also have their disadvantages. When declared as global, it will occupy memory until the program is finished, so it should only be used when necessary. Local variables only occupy memory for as long as that function is executed; when the function ends, they are destroyed.

Tags#global#local#variables
Share

Need Hosting or Servers?

Discover our VPS, dedicated servers and professional hosting solutions

Related Articles

View all articles