C++:C++ Operators: Arithmetic, Relational, and Bitwise
C++•Operators

C++ Operators: Arithmetic, Relational, and Bitwise

Explore the full spectrum of C++ operators including prefix vs postfix increment, ternary, and bitwise operations.

Syntax

result = operand1 + operand2; bitwise_and = a & b;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
++Increment++x (prefix, increments before read), x++ (postfix, increments after read).
&, |, ^BitwiseLow-level bit manipulation operators.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C++ locally:

#include <iostream>

int main() {
    int a = 20;
    int b = 6;

    std::cout << "Addition:       " << (a + b) << "\n";
    std::cout << "Integer Div:    " << (a / b) << " (truncated)\n";
    std::cout << "Float Div:      " << (static_cast<double>(a) / b) << "\n";
    std::cout << "Modulus:        " << (a % b) << "\n";

    // Bitwise shift operators
    int flags = 1; // 0001
    int shifted = flags << 3; // 1000 = 8
    std::cout << "Bitwise 1 << 3: " << shifted << "\n";

    return 0;
}
Expected Output:
Addition:       26
Integer Div:    3 (truncated)
Float Div:      3.33333
Modulus:        2
Bitwise 1 << 3: 8

How It Works: Step-by-Step

  • Lines 8-11: Shows integer division truncation and explicit floating-point cast.
  • Lines 14-16: Performs bitwise left shift (multiplying by powers of 2).

Key Concepts

  • Dividing two integers in C++ results in integer division (decimal portion truncated).
  • Use static_cast<double>() to promote operands to floating point.
  • Bitwise operators provide direct, efficient hardware bit manipulation.

Common Mistake: Expecting integer division a / b to produce a decimal fraction

In C++, 5 / 2 evaluates to 2 because both operands are integers.

❌ Incorrect
double res = 5 / 2; // Evaluates to 2.0!
✅ Correct
double res = 5.0 / 2; // Evaluates to 2.5

Related C++ Tutorials & Compiler

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler