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:
| Parameter | Type | Description |
|---|---|---|
| ++ | Increment | ++x (prefix, increments before read), x++ (postfix, increments after read). |
| &, |, ^ | Bitwise | Low-level bit manipulation operators. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C++ Variables and Primitive Data Types with Examples
Learn how to declare typed variables in C++ including int, double, char, bool, and auto.
C++ Type Casting: static_cast and Modern C++ Casts
Master compile-time type conversion using static_cast and understand modern C++ casting operators.
C++ If...Else Statements and Boolean Logic with Examples
Learn decision-making structures in C++ with if, else if, else, and C++17 init-statements.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.