Module 5: OperatorsBeginner45 min read
C++ Operators, Bitwise Operations, Precedence & Pitfalls
Comprehensive guide to arithmetic, relational, logical, bitwise, shift, ternary, and comma operators, plus precedence and common mistakes.
Key Takeaways & Core Concepts
- Arithmetic:
+,-,*,/,%(integers only). - Relational & Logical:
<,>,==,!=,&&,||,!(short-circuit evaluation). - Bitwise & Shift:
&(AND),|(OR),^(XOR),~(NOT),<<(left shift, ×2),>>(right shift, ÷2). - Increment/Decrement:
++i(pre: increments then yields new value) vsi++(post: yields old value then increments).
1. Complete Operator Categories
- Arithmetic:
+,-,*,/,%(integers only). - Relational & Logical:
<,>,==,!=,&&,||,!(short-circuit evaluation). - Bitwise & Shift:
&(AND),|(OR),^(XOR),~(NOT),<<(left shift, ×2),>>(right shift, ÷2). - Increment/Decrement:
++i(pre: increments then yields new value) vsi++(post: yields old value then increments). - Ternary & Comma:
cond ? a : b,(expr1, expr2)(evaluates left-to-right, yieldsexpr2).
1. Bitwise Tricks & Ternary Operator
1#include <iostream>
2
3int main() {
4 int n = 12; // 1100 in binary
5 bool isEven = (n & 1) == 0;
6 int doubled = n << 1;
7 std::cout << n << " is " << (isEven ? "Even" : "Odd") << ", doubled = " << doubled << "\n";
8 return 0;
9}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
9 lines
Note: `(n & 1)` checks the least significant bit to test parity in 1 CPU instruction.
2. Precedence, Associativity & Undefined Behavior
- Multiplicative (
*,/,%) binds tighter than additive (+,-), which binds tighter than bitwise shifts (<<,>>), which bind tighter than==and&&. - Critical Warning: Modifying a variable more than once in an unsequenced expression (
i = i++ + ++i;) is Undefined Behavior.
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)