Operators
C++ supports different types of operators such as arithmetic, relational, and logical operators.
Arithmetic Operators
Arithmetic operators can be used to perform common mathematical operations:
+
addition-
subtraction*
multiplication/
division%
modulo (yields the remainder)
int x = 0;x = 4 + 2; // x is now 6x = 4 - 2; // x is now 2x = 4 * 2; // x is now 8x = 4 / 2; // x is now 2x = 4 % 2; // x is now 0
Relational Operators
Relational operators can be used to compare two values and return true or false depending on the comparison:
==
equal to!=
not equal to>
greater than<
less than>=
greater than or equal to<=
less than or equal to
if (a > 10) {// ☝️ means greater than}
Logical Operators
Logical operators can be used to combine two different conditions.
&&
requires both to be true (and
)||
requires either to be true (or
)!
negates the result (not
)
if (coffee > 0 && donut > 1) {// Code runs if both are true}if (coffee > 0 || donut > 1) {// Code runs if either is true}if (!tired) {// Code runs if tired is false}