Scope Variable in C++ - Learn C++ , C++ Tutorial , C++ programming
Learn c++ - c++ tutorial - scope variable in c++ - c++ examples - c++ programs
Scope:
- Scope applies to identifiers including variable names, functions names, class names.
- A variable’s scope determines where a variable is accessible.
- A variable’s duration determines where it is created and destroyed.
- The scope of an identifier is the region of a source program within which it represents a certain thing.
- Scope is the context that gives meaning to a name
Local Variable:
- A variable defined inside a function (defined inside function body between braces) is called a local variable or automatic variable.
- Its scope is only limited to the function where it is defined. In simple terms, local variable exists and can be accessed only inside a function.
- The life of a local variable ends (It is destroyed) when the function exits.
learn c++ tutorials - global variables in c++ Example
Example 1: Local variable
- The variable var cannot be used inside test() and var1 cannot be used inside main()function.
- Keyword auto was also used for defining local variables before as: auto int var;
- But, after C++11 auto has a different meaning and should not be used for defining local variables.
Variables defined inside nested blocks are destroyed as soon as the inner block ends:
Variables in one function cannot be seen from another function:
- Variables defined inside a block can only be seen within that block. Because each function has its own block
Shadowing:
- Shadowing is when a block scope variable with the same name as a file scope variable or an ``outer'' block scope hides or shadows those variables and will be the one to be referenced.