cpp-que-son-variables

What are Variables and How to Use Them in C++

  • 3 min

An variable is a reserved space in memory with a symbolic name (identifier), in which we can store a value of a specific type.

Variables allow us to store temporary data that we can use later throughout our program.

If you want to learn more, check out the Introduction to Programming Course

Variable Declaration

Declaring a variable in C++ involves specifying its type and giving it a name. The basic syntax for declaring a variable is:

type name;
Copied!
  • type: Specifies the data type of the variable.
  • name: Is the unique name given to the variable.

For example, to declare an integer variable named age:

int age;
Copied!

Value Assignment

Assigning a value to a variable means giving it an initial value or modifying its existing value. The syntax for assigning a value to a variable is:

variableName = value;
Copied!

For example, to assign the value 25 to the variable age:

age = 25;
Copied!

It is also possible to declare and assign a variable in a single line:

int age = 25;
Copied!

Default Values

C++ does not automatically initialize variables with default values. Uninitialized local variables contain binary garbage (a random value) until a value is explicitly assigned to them.

For value types (int, float, double, char, bool, etc.), it is recommended to initialize them at the moment of declaration:

int age = 0;
float height = 0.0f;
double weight = 0.0;
char initial = '\0';
bool isStudent = false;
Copied!

For reference types (such as pointers), the default value is nullptr, which indicates that the pointer does not reference any location in memory.

int* pointer = nullptr;
std::string* string = nullptr;
Copied!

This is a frequent cause of error when using an uninitialized variable, especially when starting to program in C++ from other languages.

Volatile Variables

volatile variables indicate to the compiler that the variable’s value can change at any moment, outside the program’s control.

volatile int interrupt;
Copied!

Practical Examples

Let’s look at some simple examples of using variables in C++. These examples show how to declare and use variables to perform calculations and manage data.