C++ Variables
C++ Variables
HTML
CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C
C++ Variables
❮ Previous Next ❯
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords), for
example:
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• double - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded
by single quotes
• string - stores text, such as "Hello World". String values are surrounded by
double quotes
• bool - stores values with two states: true or false
Syntax
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C
Where type is one of C++ types (such as int ), and variableName 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:
Try it Yourself »
You can also declare a variable without assigning the value, and assign the value
later:
Example
int myNum;
myNum = 15;
cout << myNum;
Try it Yourself »
Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
Tutorials Exercises Get Certified Services
Example
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C
Try it Yourself »
Other Types
A demonstration of other data types:
Example
You will learn more about the individual types in the Data Types chapter.
Display Variables
The cout object is used together with the << operator to display variables.
To combine both text and a variable, separate them with the << operator:
Tutorials Exercises Get Certified Services
Example
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C
Try it Yourself »
Example
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
Try it Yourself »
C++ Exercises
Exercise:
Create a variable named myNum and assign the value 50 to it.
Tutorials Exercises Get Certified Services
HTML
CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C
=
Submit Answer »
COLOR PICKER
Tutorials Exercises
Services
Get Certified
HTML
CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C