Клас зберігання C ++: локальний, глобальний, статичний, регістровий та потоковий локальний

У цій статті ви дізнаєтеся про різні класи зберігання в C ++. А саме: локальний, глобальний, статичний локальний, регістр і локальний потік.

Кожна змінна в C ++ має дві особливості: тип і клас зберігання.

Тип вказує тип даних, які можна зберігати у змінній. Наприклад: int, float, і charт.д.

І клас зберігання керує двома різними властивостями змінної: тривалістю життя (визначає, як довго може існувати змінна) та сферою дії (визначає, яка частина програми може отримати до неї доступ).

Залежно від класу зберігання змінної, її можна розділити на 4 основні типи:

  • Локальна змінна
  • Глобальна змінна
  • Статична локальна змінна
  • Реєстрація змінної
  • Локальне сховище ниток

Місцева змінна

Змінна, визначена всередині функції (визначена всередині тіла функції між фігурними дужками), називається локальною змінною або автоматичною змінною.

Його сфера застосування обмежена лише функцією, де вона визначена. Простіше кажучи, локальна змінна існує, і доступ до неї можна отримати лише всередині функції.

Життя локальної змінної закінчується (вона руйнується), коли функція виходить.

Приклад 1: Локальна змінна

 #include using namespace std; void test(); int main() ( // local variable to main() int var = 5; test(); // illegal: var1 not declared inside main() var1 = 9; ) void test() ( // local variable to test() int var1; var1 = 6; // illegal: var not declared inside test() cout << var; )

Змінну var не можна використовувати всередині, test()а var1 не можна використовувати всередині main()функції.

Ключове слово autoраніше також використовувалося для визначення локальних змінних як:auto int var;

Але після того, як C ++ 11 autoмає інше значення і не повинен використовуватися для визначення локальних змінних.

Глобальна змінна

Якщо змінна визначена поза усіма функціями, тоді вона називається глобальною змінною.

Сфера дії глобальної змінної - це ціла програма. Це означає, що його можна використовувати та змінювати в будь-якій частині програми після її оголошення.

Так само його життя закінчується лише тоді, коли закінчується програма.

Приклад 2: Глобальна змінна

 #include using namespace std; // Global variable declaration int c = 12; void test(); int main() ( ++c; // Outputs 13 cout << c < 

Output

 13 14

In the above program, c is a global variable.

This variable is visible to both functions main() and test() in the above program.

Static Local variable

Keyword static is used for specifying a static variable. For example:

… int main() ( static float a;… ) 

A static local variable exists only inside a function where it is declared (similar to a local variable) but its lifetime starts when the function is called and ends only when the program ends.

The main difference between local variable and static variable is that, the value of static variable persists the end of the program.

Example 3: Static local variable

 #include using namespace std; void test() ( // var is a static variable static int var = 0; ++var; cout << var << endl; ) int main() ( test(); test(); return 0; )

Output

 1 2

In the above program, test() function is invoked 2 times.

During the first call, variable var is declared as static variable and initialized to 0. Then 1 is added to var which is displayed in the screen.

When the function test() returns, variable var still exists because it is a static variable.

During second function call, no new variable var is created. The same var is increased by 1 and then displayed to the screen.

Output of above program if var was not specified as static variable

 1 1

Register Variable (Deprecated in C++11)

Keyword register is used for specifying register variables.

Register variables are similar to automatic variables and exists inside a particular function only. It is supposed to be faster than the local variables.

If a program encounters a register variable, it stores the variable in processor's register rather than memory if available. This makes it faster than the local variables.

However, this keyword was deprecated in C++11 and should not be used.

Thread Local Storage

Thread-local storage is a mechanism by which variables are allocated such that there is one instance of the variable per extant thread.

Keyword thread_local is used for this purpose.

Learn more about thread local storage.

Цікаві статті...