C++ Variables

In C++, Variables are used to store the values. In reality, variable is a location in memory which can be accessed using a symbolic name given to the variable.

In C++, a variable is declared with a datatype and a name. The datatype determines the type of data that can be stored in that variable.

Declare Variable(s)

The syntax to declare a variable is

datatype name;

where

datatype is the type of data that is allowed to store in this variable, and name is the name of the variable through which we can access the value stored in variable.

In the following, we declared a variable with name x, and type int.

int x;

We can define more than one variable in a single statement using the following syntax.

datatype v1, v2, v3;

where v1, v2 and v3 are variables.

In the following, we declared three variables: x, y and z of type int in a single statement.

int x, y, z;

Initialise Variable(s)

The syntax to initialise a variable using assignment operator is

datatype name = value;

where

value is the initial value assigned to the variable.

In the following, we initialised variable x with value 25.

int x = 25;

We can initialise more than one variable in a single statement using the following syntax.

datatype v1 = value, v2 = value, v3 = value;

where v1, v2 and v3 are variables.

In the following, we initialise three variables: x, y and z of type int with different values in a single statement.

int x = 0, y = 5, z = 9;

Conclusion

In this C++ Tutorial, we learned what variables are in C++, and how to use declare and initialise variables, with the help of examples.