1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M2 Logical
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
11Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M2 Logical

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
11Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Logical & Bitwise

Overview

To build intelligent applications, your code must make complex decisions combining multiple conditions. Logical Operators (&& AND, || OR, ! NOT) handle standard boolean logic.

However, because C++ is used to program hardware (like Arduino or networking routers), it also provides Bitwise Operators (&, |, ^, <<). These operate at the absolute lowest level possible—manipulating the individual binary 1s and 0s inside a variable's memory space. This is how high-performance game engines pack 8 boolean flags into a single byte of memory.

Syntax

cpp
bool isWeekend = true;
bool hasMoney = false;

// --- 1. LOGICAL OPERATORS (Evaluating Truth) ---
// AND: Both must be true
bool goOut = isWeekend && hasMoney; // false

// OR: At least one must be true
bool stayHome = !isWeekend || !hasMoney; // true

// --- 2. BITWISE OPERATORS (Manipulating Binary) ---
int x = 5;  // Binary: 0101
int y = 3;  // Binary: 0011

int bitAnd = x & y;  // 0001 (Decimal 1)
int bitOr  = x | y;  // 0111 (Decimal 7)
int bitXor = x ^ y;  // 0110 (Decimal 6)

// Bitwise Left Shift (Mathematically multiplies by 2!)
int shift = x << 1;  // 1010 (Decimal 10)

Common Pitfalls

  • Using a single & when you meant &&. if (x > 5 & y < 10) will execute a Bitwise operation instead of a Logical evaluation. While it sometimes accidentally works, it completely bypasses 'Short-Circuiting', destroying your performance.
  • Not understanding 'Short-Circuit Evaluation'. In if (A && B), if A is false, C++ completely ignores B (it doesn't even execute the code for B) because the statement is already mathematically guaranteed to be false.

Interview Questions

Why do low-level C++ engineers use the Bitwise Left Shift operator (<< 1) to multiply a number by 2, instead of standard multiplication (* 2)?

Standard multiplication requires the CPU's Arithmetic Logic Unit (ALU) to perform complex algorithmic math, taking multiple CPU cycles. A Bitwise Shift physically nudges the bits to the left in the hardware register, taking exactly 1 CPU cycle. It is the absolute fastest way to multiply or divide by powers of 2.

Real-World Example

Using Bitwise Operators to pack multiple boolean settings into a single 8-bit integer, saving massive amounts of RAM in networking packets.

example
cpp
const unsigned char FLAG_READ  = 1 << 0; // 0001
const unsigned char FLAG_WRITE = 1 << 1; // 0010
const unsigned char FLAG_EXEC  = 1 << 2; // 0100

// Combine permissions using Bitwise OR (|)
unsigned char userPerms = FLAG_READ | FLAG_WRITE; // 0011

// Check a specific permission using Bitwise AND (&)
if (userPerms & FLAG_READ) {
    // User is allowed to read!
}

Check Your Knowledge

Test your understanding of Logical & Bitwise with these quick questions.

Question 1

Due to 'Short-Circuit Evaluation', what happens if you run the code: `if (false && expensiveFunction())`?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Logical & Bitwise

Overview

To build intelligent applications, your code must make complex decisions combining multiple conditions. Logical Operators (&& AND, || OR, ! NOT) handle standard boolean logic.

However, because C++ is used to program hardware (like Arduino or networking routers), it also provides Bitwise Operators (&, |, ^, <<). These operate at the absolute lowest level possible—manipulating the individual binary 1s and 0s inside a variable's memory space. This is how high-performance game engines pack 8 boolean flags into a single byte of memory.

Syntax

cpp
bool isWeekend = true;
bool hasMoney = false;

// --- 1. LOGICAL OPERATORS (Evaluating Truth) ---
// AND: Both must be true
bool goOut = isWeekend && hasMoney; // false

// OR: At least one must be true
bool stayHome = !isWeekend || !hasMoney; // true

// --- 2. BITWISE OPERATORS (Manipulating Binary) ---
int x = 5;  // Binary: 0101
int y = 3;  // Binary: 0011

int bitAnd = x & y;  // 0001 (Decimal 1)
int bitOr  = x | y;  // 0111 (Decimal 7)
int bitXor = x ^ y;  // 0110 (Decimal 6)

// Bitwise Left Shift (Mathematically multiplies by 2!)
int shift = x << 1;  // 1010 (Decimal 10)

Common Pitfalls

  • Using a single & when you meant &&. if (x > 5 & y < 10) will execute a Bitwise operation instead of a Logical evaluation. While it sometimes accidentally works, it completely bypasses 'Short-Circuiting', destroying your performance.
  • Not understanding 'Short-Circuit Evaluation'. In if (A && B), if A is false, C++ completely ignores B (it doesn't even execute the code for B) because the statement is already mathematically guaranteed to be false.

Interview Questions

Why do low-level C++ engineers use the Bitwise Left Shift operator (<< 1) to multiply a number by 2, instead of standard multiplication (* 2)?

Standard multiplication requires the CPU's Arithmetic Logic Unit (ALU) to perform complex algorithmic math, taking multiple CPU cycles. A Bitwise Shift physically nudges the bits to the left in the hardware register, taking exactly 1 CPU cycle. It is the absolute fastest way to multiply or divide by powers of 2.

Real-World Example

Using Bitwise Operators to pack multiple boolean settings into a single 8-bit integer, saving massive amounts of RAM in networking packets.

example
cpp
const unsigned char FLAG_READ  = 1 << 0; // 0001
const unsigned char FLAG_WRITE = 1 << 1; // 0010
const unsigned char FLAG_EXEC  = 1 << 2; // 0100

// Combine permissions using Bitwise OR (|)
unsigned char userPerms = FLAG_READ | FLAG_WRITE; // 0011

// Check a specific permission using Bitwise AND (&)
if (userPerms & FLAG_READ) {
    // User is allowed to read!
}

Check Your Knowledge

Test your understanding of Logical & Bitwise with these quick questions.

Question 1

Due to 'Short-Circuit Evaluation', what happens if you run the code: `if (false && expensiveFunction())`?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A