To create a variable, you must specify the type and assign it a value:
Syntax
type variable = value;
Where type is one of C++ types (such as int
), and variable is the name of the variable (such as x or myName). The equal sign is used to assign values to the variable.
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int
and assign it the value 15:
int myNum = 15;
cout << myNum;
cout << myNum;
You can also declare a variable without assigning the value, and assign the value later:
Example
int myNum;
myNum = 15;
cout << myNum;
myNum = 15;
cout << myNum;
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
Practice Excercise Practice now