| type | explanation | example |
|---|---|---|
int | integer | 12 |
double | floating point | 4.5 |
char | character | 'm' |
string | string | "monkey" |
bool | boolean | true |
int,
called a.
int a;In the above case, the variable is uninitialized, so it may start with any value that is already in memory. So you can't rely on a variable to have a value initially, for example, 0. However, we can provide in connection with the definition the desired initial value for the variable as follows:
int a = 5;You can define multiple variables at once, as long as their types are the same. For example, the following code defines two
int variables:
int a, b;The variable type is fixed, and cannot be changed after definition.
int a = 2, b = 5; cout << a << " " << b << "\n"; // 2 5 a = 3; b = a+b; cout << a << " " << b << "\n"; // 3 8If the new value of a variable is calculated based on its old value, can use operators
+=, -=, *=, /=, etc.
For example, the following code snippets have the same meaning:
a = a+5; b = b*2;
a += 5; b *= 2;Also, if the value of a variable increases or decreases by one, we can use
++ and -- operators.
For example, the following codes have the same meaning:
a++; b--;
a = a+1; b = b-1;
=
is actually an expression,
whose value is the new value of the variable.
For example, in the following code, an expression
a = 3 has a value of 3,
so the code sets a to 3
and b to 5.
b = 2 + (a = 3);This allows us to set the value of many variables at the same time. For example, the following code sets the variables
a and b to 1:
a = b = 1;In this case, the interpretation is that the variables are set right to left.
For ++ and -- operators
the value of the expression depends on
which side the operator is.
If the operator is after the variable,
the value of the expression is the old value of the variable,
and if the operator is ahead of the variable,
the expression value is the new value for the variable.
The following codes illustrate this:
int a = 3; cout << a++ << "\n"; // 3
int a = 3; cout << ++a << "\n"; // 4You can use a comma to combine multiple expressions into one expression whose value is the value of the last expression. For example, the value of
a = 2, b = 5 is 5.
swap,
which interchanges the contents of two variables:
swap(a,b);This will produce the same result as the following code, with auxiliary variable
t:
t = a; a = b; b = t;
const keyword.
For example, the following code creates a constant variable, with a value of 5.
const int n = 5;The benefit of such a definition is that the variable is blocked by the compiler from changing. For example, the following code does not work, because it is trying to change the value of a constant variable.
const int n = 5 n = 8; // doesn't work