In this section, let us explore variable scope in C++. By scope, we mean an area of a block in a program. It is a region of the program and more or less there are 3 scope levels defined for a variable −
- Local scope when it is defined inside a function or a block and accessible only in that block.
- Formal scope when it is defined as a function parameters.
- Global scope when it is defined outside of all functions.
Let us drill down each variable scope. Local variables are defined inside functions or a block in a function and are local to it. The variable has no scope outside that function or block. Global variables have scope in the entire program. It is usually defined outside of all the functions and usually on top of the program. The global variables will hold their value throughout the life-time of your program. A global variable can be accessed by any function in the file and is available for use for the entire duration of the program after its declaration.
We can use same name for local and global variables but value of local variable inside a function will take precedence. Also note that a local variable is declared, it is not initialized by the system. It is up to the user to initialize it. Global variables are initialized automatically by the system after you declare them.