C++ Variable Scope

In this tutorial you will learn about the C++ Variable Scope and its application with practical example.

C++ Variable Scope

What Is Variable Scope?

Scope defines the region of visibility or availability for a variable, out of which we can not reference that variable. In C++, variable declared inside main() function can not be accessed outside the main() function. Scope of a variable is limited to the curly braces containing it, if you try to access that variable outside those curly braces then you will get compilation error. In C++, variables can be of following two types based on their scope.

  • Global Variables
  • Local Variables

C++ Global Variable

Global variables can be accessed at any point throughout the program, and can be used in any function. There is single copy of the global variable is available. Global variables are defined outside of all the functions, usually on top of the main() function.

Example:-

Output:-

cpp_global_variable

C++ Local Variable

Variable declared inside a function or block of code are called local variables. They can be accessed only inside that function or block of code. Local variables are not available outside the function it is defined in.

Recommended:-  C++ Comments

Example:-

Output:-

cpp_local_variable

Note :- A program can have same name for local and global variables but local variable overrides the value.

In this tutorial we have learn about the C++ Variable Scope and its application with practical example. I hope you will like this tutorial.