Global Variable in C++

Global variables are the variables that are declared outside of any function or class and can be accessed by any part of the program. They are generally declared at the beginning of the source file after the header file. They are available throughout the lifetime of a program and accessible from anywhere within the program.

C++ Global Variables

In C++ programming languages, a variable is a name provided to memory to store different data types. Variable values can change anytime while running the program and each variable has its own scope (or region) where it is valid to access the variable using the name given to him.

In programming, variables are not all equal. Their scope, lifespan, and accessibility in the program depend on where and how they are declared. There are two types of variables based on their scope.

  1. Local variable – The scope of these variables exists only within the block in which the variable is declared. i.e. we can access this variable only within that block.
  2. Global variable – Global variables are a special type with the widest scope possible. It is declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program.

Similar Reads

Global Variable in C++

Global variables are the variables that are declared outside of any function or class and can be accessed by any part of the program. They are generally declared at the beginning of the source file after the header file. They are available throughout the lifetime of a program and accessible from anywhere within the program....

Declaration of a Global Variable in C++

To create a global variable, we simply declare it at the top of the source file, after the header files, and before the main function. In C++, all the variables must be declared before use....

Benefits of Using Global Variables

...

Drawbacks of Using Global Variables

...

Conclusion

Following are some main benefits that global variables provide:...

Contact Us