operators
C++ provides a wide variety of operators including arithmetic, comparison, logical, and bitwise operators, allowing concise expression of everything from numeric calculations to conditional branching and bit manipulation. Understanding operator precedence and associativity ensures the calculation results you intend.
Syntax
// --- Arithmetic operators --- a + b // Addition a - b // Subtraction a * b // Multiplication a / b // Division (truncates decimal for integer operands) a % b // Remainder (modulo) // --- Compound assignment operators --- a += b // Same as a = a + b a -= b // Same as a = a - b a *= b // Same as a = a * b a /= b // Same as a = a / b a %= b // Same as a = a % b // --- Increment / Decrement --- ++a // Pre-increment: returns value after increment a++ // Post-increment: returns value before increment --a // Pre-decrement: returns value after decrement a-- // Post-decrement: returns value before decrement // --- Comparison operators (result is bool) --- a == b // Equal a != b // Not equal a < b // Less than a > b // Greater than a <= b // Less than or equal a >= b // Greater than or equal // --- Logical operators --- a && b // Logical AND: true when both sides are true a || b // Logical OR: true when either side is true !a // Logical NOT: inverts true/false // --- Bitwise operators --- a & b // Bitwise AND a | b // Bitwise OR a ^ b // Bitwise XOR ~a // Bitwise NOT (one's complement) a << n // Left shift (shift a by n bits to the left) a >> n // Right shift (shift a by n bits to the right) // --- Ternary operator --- condition ? valueIfTrue : valueIfFalse
Operator Reference
| Operator / Category | Description |
|---|---|
| + - * / % | Basic arithmetic operators. / truncates the decimal when both operands are integers. |
| += -= *= /= %= | Compound assignment operators that combine arithmetic and assignment. |
| ++a / a++ | Pre-increment returns the value after incrementing; post-increment returns the value before incrementing. |
| --a / a-- | Pre-decrement returns the value after decrementing; post-decrement returns the value before decrementing. |
| == != | Equality comparison operators. The result is of type bool (true / false). |
| < > <= >= | Relational operators. Used in conditional expressions and sorting. |
| && | Logical AND operator. The right side is not evaluated if the left side is false (short-circuit evaluation). |
| || | Logical OR operator. The right side is not evaluated if the left side is true (short-circuit evaluation). |
| ! | Logical NOT operator. Inverts true to false and false to true. |
| & | ^ ~ | Bitwise AND / OR / XOR / NOT operations. Used for flag management and cryptographic processing. |
| << >> | Left and right shift operators. One-bit left shift equals ×2; right shift equals ÷2. |
| condition ? a : b | Ternary operator. Returns a if condition is true, b if false. |
Sample Code
yakuza_battle.cpp
#include <iostream>
#include <string>
int main() {
// --- Initial HP and damage values ---
int kiryu_hp = 500;
int majima_hp = 480;
int kiryu_atk = 120;
int majima_atk = 135;
int defense = 30;
std::cout << "=== Yakuza Battle Simulator ===" << std::endl;
// --- Arithmetic operators: calculate damage ---
int damage_to_majima = kiryu_atk - defense;
int damage_to_kiryu = majima_atk - defense;
std::cout << "Kiryu's damage to Majima: " << damage_to_majima << std::endl;
std::cout << "Majima's damage to Kiryu: " << damage_to_kiryu << std::endl;
// --- Compound assignment operators: update HP ---
majima_hp -= damage_to_majima;
kiryu_hp -= damage_to_kiryu;
std::cout << "Kiryu's remaining HP: " << kiryu_hp << std::endl;
std::cout << "Majima's remaining HP: " << majima_hp << std::endl;
// --- Comparison operators: determine winner ---
std::cout << "\n--- Result ---" << std::endl;
if (kiryu_hp > majima_hp) {
std::cout << "Kiryu Kazuma wins!" << std::endl;
} else if (kiryu_hp < majima_hp) {
std::cout << "Majima Goro wins!" << std::endl;
} else {
std::cout << "Draw!" << std::endl;
}
// --- Logical operators: state check ---
bool kiryu_alive = (kiryu_hp > 0);
bool majima_alive = (majima_hp > 0);
if (kiryu_alive && majima_alive) {
std::cout << "Both fighters can still fight." << std::endl;
}
if (!kiryu_alive || !majima_alive) {
std::cout << "One fighter has been defeated." << std::endl;
}
// --- Increment / Decrement: round management ---
int round = 1;
std::cout << "\nCurrent round: " << round << std::endl; // 1
std::cout << "After post-increment: " << round++ << std::endl; // 1 (returns pre-increment value)
std::cout << "After pre-increment: " << ++round << std::endl; // 3 (returns post-increment value)
// --- Modulo operator: turn determination ---
for (int turn = 1; turn <= 4; ++turn) {
std::string attacker = (turn % 2 != 0) ? "Kiryu Kazuma" : "Majima Goro";
std::cout << "Turn " << turn << " first strike: " << attacker << std::endl;
}
// --- Bitwise operators: flag management ---
const int FLAG_HEAT_MODE = 1 << 0; // Bit 0: Heat mode (1)
const int FLAG_GUARD_UP = 1 << 1; // Bit 1: Guard boost (2)
const int FLAG_BERSERK = 1 << 2; // Bit 2: Berserk mode (4)
int kiryu_flags = 0;
kiryu_flags |= FLAG_HEAT_MODE;
kiryu_flags |= FLAG_GUARD_UP;
std::cout << "\n--- Kiryu's Status Flags ---" << std::endl;
std::cout << "Heat Mode: " << ((kiryu_flags & FLAG_HEAT_MODE) ? "ON" : "OFF") << std::endl;
std::cout << "Guard Boost: " << ((kiryu_flags & FLAG_GUARD_UP) ? "ON" : "OFF") << std::endl;
std::cout << "Berserk: " << ((kiryu_flags & FLAG_BERSERK) ? "ON" : "OFF") << std::endl;
kiryu_flags ^= FLAG_HEAT_MODE;
std::cout << "After disabling Heat Mode: " << ((kiryu_flags & FLAG_HEAT_MODE) ? "ON" : "OFF") << std::endl;
// --- Shift operators: damage multiplier ---
int base_damage = 50;
std::cout << "\n--- Damage multiplier via shift ---" << std::endl;
std::cout << "Normal damage: " << base_damage << std::endl;
std::cout << "Heat move x2: " << (base_damage << 1) << std::endl;
std::cout << "Finisher x4: " << (base_damage << 2) << std::endl;
return 0;
}
g++ -std=c++17 yakuza_battle.cpp -o yakuza_battle ./yakuza_battle === Yakuza Battle Simulator === Kiryu's damage to Majima: 90 Majima's damage to Kiryu: 105 Kiryu's remaining HP: 395 Majima's remaining HP: 390 --- Result --- Kiryu Kazuma wins! Both fighters can still fight. Current round: 1 After post-increment: 1 After pre-increment: 3 Turn 1 first strike: Kiryu Kazuma Turn 2 first strike: Majima Goro Turn 3 first strike: Kiryu Kazuma Turn 4 first strike: Majima Goro --- Kiryu's Status Flags --- Heat Mode: ON Guard Boost: ON Berserk: OFF After disabling Heat Mode: OFF --- Damage multiplier via shift --- Normal damage: 50 Heat move x2: 100 Finisher x4: 200
Common mistake 1: Forgetting that integer division truncates the decimal
Integer / division truncates the decimal part. When a floating-point result is needed, convert one operand to a floating-point type before the calculation.
// NG: Integer division truncates the decimal int kiryu_hp = 395; int total_hp = 500; int percent = (kiryu_hp / total_hp) * 100; // Becomes 0 (truncated before multiplying) std::cout << percent << std::endl; // 0
OK: Cast to double using static_cast before dividing.
// OK: Cast one operand to double first int kiryu_hp = 395; int total_hp = 500; double percent = (static_cast<double>(kiryu_hp) / total_hp) * 100.0; std::cout << percent << std::endl; // 79
Common mistake 2: Confusing pre-increment and post-increment
Pre-increment (++a) returns the value after incrementing; post-increment (a++) returns the value before incrementing. This difference matters when used inside expressions.
// Difference: post-increment returns the pre-increment value in the expression int round = 1; std::cout << round++ << std::endl; // 1 (prints pre-increment value; round becomes 2) std::cout << round << std::endl; // 2 // Pre-increment returns the post-increment value int round2 = 1; std::cout << ++round2 << std::endl; // 2 (prints post-increment value)
OK: For simple increment in a loop counter where the value is not used, either form produces the same result.
// Both ++i and i++ produce the same behavior as a loop counter
for (int i = 0; i < 5; ++i) {
// ...
}
Overview
Arithmetic operators (+ - * / %) are the most fundamental operators. Note that integer division truncates the decimal part. Compound assignment operators (+=, etc.) combine arithmetic and assignment into one line, making update operations like HP changes concise. Increment (++) and decrement (--) have prefix and postfix forms; when used inside an expression, the key difference is "prefix returns the value after change; postfix returns the value before change." Comparison operators all return bool, used in if and while conditions. Logical operators (&& ||) use short-circuit evaluation — if the left side determines the overall truth value, the right side is not evaluated. Bitwise operators are useful for flag management, cryptographic processing, and fast integer arithmetic. The typical patterns are OR (|) to set a flag, AND (&) to check a specific bit, XOR (^) to toggle a specific bit, and shift operators (<< >>) for powers-of-two multiplication/division. The ternary operator (condition ? a : b) is commonly used to express short conditional branches in one line, but for complex conditions, if-else is more commonly used.
If you find any errors or copyright issues, please contact us.