The life span of variables

Location
  1. Courses

    /

  2. Complete C++ Course

    /

  3. The basics

    /

  4. The life span of variables

Contexts

Variables only exist within their context. That means that if we define a variable between braces {}, then once the end of the braces is reached, the variable does not exist anymore. The braces {} a variable is defined in is called its scope.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main() { int n = 3; if(n == 3) { int n2 = 5; // Here, n and n2 exist. int n3 = 6; // Here, n, n2 and n3 exist. } // Here, only n exists. n3 = 50; // Error: n3 does not exist here. // We can define an another variable named n2, since it does not exist here. int n2 = 9; return 0; }

When we define a variable inside the parentheses of a control structure, it exists (And only) inside the braces following it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main() { int var1 = 1; if(int var2 = var1) { // Here, var2 exists. var2 = 92; } // Here, var2 does not exist. return 0; }

Limit the life span of a variable

It is possible the use braces {} alone, for the only purpose of limiting the life span of a variable.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main() { int n = 5; int n2 = 8; { int n3 = n; n = n2; n2 = n3; } // Here, the variable n3 does not exist anymore. return 0; }

In the example above, the variable n3 is simply used to temporary hold the value of n in order to switch the values of n and n2. In that case, since we only need n3 for a short moment, we can define it inside braces so it stops existing after we are done using it.

Global variables

A variable that is not defined inside any braces {} is called a global variable. Such variables exist everywhere in the code since their scope is the whole program. It is strongly recommended to never define global variables that are not constant as it likely to cause mistakes (If their value is changed by mistake, it might be hard to find where in the code it has been changed, since it could be anywhere). Basically, a constant variable is a variable which value can not change after it has been defined. We will learn more about constant variables later.