1.4 Expressions and Operators
An expression combines values, variables, and operators. Programs use expressions to calculate, compare, and update data.
Arithmetic operators
C++ supports common addition, subtraction, multiplication, and division, plus the modulo operation.
+,-,*: add, subtract, multiply/: division%: modulo (remainder)
When two integers are divided, C++ performs integer division and truncates the fractional part.
std::cout << 22 / 3 << std::endl; // 7
std::cout << 22 % 3 << std::endl; // 1To get a decimal result, at least one operand must be floating point.
std::cout << 22 / 3.0 << std::endl; // 7.33333Reversing a three-digit integer
Integer division and modulo are often used together to split an integer into digits.
int num = 520;
int a = num / 100;
int b = num / 10 % 10;
int c = num % 10;
std::cout << c * 100 + b * 10 + a << std::endl;Output:
25The result is displayed as 25 because the reversed number is 025, and leading zeros are not shown when printing an integer.
Compound operators
Compound assignment operators make variable updates shorter.
a += bmeansa = a + ba -= bmeansa = a - ba *= bmeansa = a * ba /= bmeansa = a / ba %= bmeansa = a % b
Increment and decrement
C++ also provides the increment operator ++ and decrement operator --, which add 1 or subtract 1 from a variable. They are very common in loop counters.
int i = 5;
i++; // i becomes 6
i--; // i becomes 5i++ is equivalent to i = i + 1, and i-- is equivalent to i = i - 1.