Tutorial: Variables in C++

In this tutorial, we will learn about variables in C++. We use variables in our program to store different types of values and carry out operations. Let’s discuss it in detail.

Variables in C++

Variables, in C++, are like containers to store values. These are names to some memory location whose value can vary. Therefore, we call them variables.

Example:

int var;
var=10;

Here, int declares the data type of a variable var which is an integer. A memory location is assigned to var then 10 is stored in that memory location. We can access and modify the value of that location using var. Thus we can say that a variable is much like a pointer to a memory location.

Naming a variable: We can name a variable using alphabets, numbers, and underscore(‘_’) character. Keep in mind though, a variable name cannot start with a number. See the examples.

int _var;
char var;
char Var_;
float _1VAR;
double _var1;

The compiler will throw an error if we start the variable name with a number. See the code.

#include <iostream>

int main()
{
  //variable name starting with a number
  int 1a;   
  std::cout<<1a;
  
  return 0;
}

Output:

Error

 

Types of variables in C++ based on the data type

There are the following types of variables based on their data type:

 

S. No. Type Description
1 int for storing integer values.
2 char for storing characters and strings.
3 bool for storing true and false.
4 float for storing single-precision floating-point values.
5 double for storing double-precision floating-point values.
6 wchar_t for storing wide-character type values.
7 void It does not store any type of value.

There are also many other types of variables in C++ such as pointers, enumerated variables, array, and different data structures.

To read about the classification of variables based on their scope, See Scope of variables in C++

Variable declaration and definition

A variable declaration tells the compiler the name of the variable, its type and the value it holds initially while a variable definition assigns a memory location to the variable and initializes it with the provided value.

In C++, a variable normally is declared and defined at the same time. For example,

int var=10;

Here var is declared and assigned some memory location with value 10.

If we want to only declare a variable and not define it right away, we can use the extern keyword. Learn about it here: Storage Classes In C++

Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *