C++ 2
C++ 2
In C++, there are different types of variables (defined with different keywords),
for example:
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:
#include <iostream>
int main() {
int myNum = 15;
return 0;
}Run example »
You can also declare a variable without assigning the value, and assign the
value later:
Example
#include <iostream>
using namespace std;
int main() {
int myNum;
myNum = 15;
cout << myNum;
return 0;
}
Run example »
Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
Example
#include <iostream>
using namespace std;
int main() {
int myNum = 15; // Now myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum;
return 0;
}
RunRun example » example »
Constants
However, you can add the const keyword if you don't want others (or yourself)
to override existing values (this will declare the variable as "constant", which
means unchangeable and read-only):
Example
#include <iostream>
using namespace std;
int main() {
const int myNum = 15;
myNum = 10;
cout << myNum;
return 0;
}Run example »
Other Types
A demonstration of other data types:
Example
int myNum = 5; // Integer (whole number without
decimals)
double myFloatNum = 5.99; // Floating point number (with
decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
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:
Example
#include <iostream>
using namespace std;
int main() {
int myAge = 35;
cout << "I am " << myAge << " years old.";
return 0;
}Run example »
Example
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
return 0;
}Run example »
Example
#include <iostream>
using namespace std;
int main() {
int x = 5, y = 6, z = 50;
cout << x + y + z;
return 0;
}
Run example »
C++ Identifiers
All C++ variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are: