Local and Global variables in C++ | variable types

Опубликовано: 30 Сентябрь 2024
на канале: it Tips
168
4

There are different storage access specifiers in C and C++. These specifiers can be used with variable declaration. Each storage access specifier has different properties. In today video session we have discussed the following Four variable types.
1. Local variable
2. Global variable
3. Static Variable
4. Register Variable
While declaring variables in program we have to decide what is the purpose of the variable and what will the use of this variable throughout the program. It is good programming practice to choose the best appropriate storage access specifier while declaration the variables.
The first type of variable are most commonly used and this is the default type of variable. It is called local variable. Storage access specifier for local variables is auto. But this is not necessary to use auto keyword in declaration of local variables. That's why local variables are also called auto variables. These variables are declared inside function body and not accessible outside of the function. When the control transfer outside from the function these variables are destroyed and no more exist inside memory. At the time of new function call local variables are created again.
Global variables are such type of variables that are declared outside of all function definition. These are not created inside any function decimeters. Global variables are accessible in entire program. Global variables remain in main memory until program termination.
Static variables are also declared inside function body such as auto or local variables. But lifetime of static variables is similar to global variables. Static variables cannot declared as register variables.
The last type of variable is register variable. Register variables are created inside CPU register and has faster access time. Register variables cannot created as global variable. Normally register variables are declared for loop iterations.Register variables are best for counter variables.