Variables in C++

Nitin
2 min readAug 15, 2021

A variable is simply a storage unit for our data. Just like in real life we have different containers to store different objects similarly, we require different amounts of memory to store different types of data.

Variable declaration

#include <iostream>int main() {
//variable declaration
int a;
//variable assignment
a = 10;

//varaible declaration and assignment
char c = 'a';
//multiple variable declarations
int b,c,d;
}

Rules for defining variables

  1. A variable can have alphabets, numerics, and underscore.
  2. A variable name must not start with a numeric.
  3. A variable name cannot contain white space.
  4. Any reserved keyword cannot be used as a variable name (eg. switch, for)

Types of variables in C++

  • Local variable: A local variable is declared inside a function or block. The scope of the variable is limited to the function or block.
int foo() {
int x = 10; // local variable
...
return x;
}
  • Global variable: A global variable is declared outside of any block or function. It is declared at the beginning of the program and can be accessed throughout the program.
#include <iostream>
int x = 100; // global variable
int foo() {
x = 500; // x variable accessible here
...
}
int main() {
x = 20; // x accessible here
return 0;
}
  • Static variable: A static variable is a variable that has been allocated statically which means its lifetime is the entire run of the program. In simpler words, a static variable retains its value during multiple function calls.
#include <iostream>int function() {
int x = 10;
static int y = 10;
x = x + 10;
y = y + 10;
std::cout << x << " " << y << std::endl;
return 0;
}
int main() {
function();
function();
function();
return 0;
}
OUTPUT:
20 20
20 30
20 40
(In the above example notice that the variable x keeps going back to its initial value whereas variable y retains its value from previous function call.)

To learn more about different data types in c++: https://niftynitin.medium.com/data-types-in-c-a4afd1da4b33

--

--

Nitin

I am a CS graduate and an ML enthusiast. My purpose here is to guide beginners in their programming and Machine learning journey.