[C++] Variables

binh12A3
3 min readOct 25, 2021

--

local, global, static, extern…😎😎

When a program run to “int iCount = 0;” then an area in RAM will be allocated for this variable.

When talk about variables, there 2 things we should know :

  • Scope of variable : global, local,…
  • The lifetime of the variable : when the variable is destroyed or when the allocated memory in RAM of variable is free

Overview

  • If you don’t initialize the value of variable, it’ll have a dummy value. So it’s a good practice to initialize the value of variable when you declare it.
  • Types of initializations

1. Local variable

  • Variable which is defined inside a block.
  • It has block scope. Which mean, we can access this variable outside the block.
  • It has dynamic time which means it’s created when we defined, and destroyed when we exit the block contains it.
  • We could have variables with the same name in different blocks. When in a nested-block, there is a variable with the same name, then the program will hide the variable outiside. We could do it but it’s not recommended, it’s better we we name it differently.
  • We should define a variable in the nearest place we use it.

2. Global variable

  • Variable which is defined outside a block
  • It has global scope, file scope or global namespace scope.
  • It has static time which means it’s created when a program starts, and destroyed when a program ends.
  • It’s defined in the beginning of the file, below “#include”.
  • We should prevent using global variable, since it’s risky especially in big and complex program. We should prefer using local variable. It’s risky because everywhere could call and change global variable , so it’s hard to manage it. We could use global constant to walk around it, since the constant value is unchanged.
  • The global variable will reduce the flexibility of your sub functions. i.e : we can’t reused sub functions in other programs which don’t have such that global variable.
  • We can use “::” to point global variable when we have duplicated variables.

3. Static variable

  • When we use “static” keyword with local variable, then it’ll become static variable.
  • Static variable is a combination of global and local variable.
  • Static variable is created only 1 time, at the 1st time we call it, and alive until a program ends. (global)
  • Static variable can be accessed only in the block where define it. (local)

Demo :

Here we can see that the static variable s_iCount is not destroyed and continue increasing in next calls.

  • There are 2 types of static variable : internal linkage and external linkage.
  • When we should use static variable ? When we want to store the value of variable during a program. i.e : a func to generate unique id which is kept increasing during a program.

--

--

binh12A3
binh12A3

Written by binh12A3

share to be shared 😎 Made in 🇻🇳

No responses yet