1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M3 If
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
00Hrs
57Mins
47Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M3 If

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
00Hrs
57Mins
47Secs
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++

If...Else

Overview

Programs are useless if they execute the exact same instructions every time they run. They need the ability to make decisions based on dynamic variables. The if...else statement is the fundamental building block of logic in C++.

It evaluates a boolean expression (a statement that resolves to true or false). If the condition is true, it executes the block of code inside the curly braces. If false, it completely ignores that block and moves on to the else block. In highly optimized, performance-critical C++ applications (like Unreal Engine), developers must be incredibly careful with complex if statements due to a hardware concept called 'Branch Prediction', where the CPU tries to guess which path the if statement will take to save time.

Syntax

cpp
int score = 85;

// 1. Basic If-Else
if (score >= 90) {
    std::cout << "Grade: A\n";
} 
// 2. Chained Conditions
else if (score >= 80) {
    std::cout << "Grade: B\n";
} 
// 3. Fallback
else {
    std::cout << "Grade: C or lower\n";
}

Common Pitfalls

  • The Assignment vs. Equality bug. Writing if (score = 100) is a catastrophic logic error. The single = is an assignment operator. It physically changes the score to 100, which evaluates to true, meaning the 'If' block will always execute! You MUST use the double == for equality checking: if (score == 100).
  • Omitting the curly braces {}. If you write an if statement without curly braces, C++ will only apply the condition to the very first line of code beneath it. The second line will execute unconditionally, leading to incredibly confusing bugs.

Interview Questions

Explain what 'Branch Prediction' is and why highly unpredictable if statements inside massive loops slow down C++ programs.

Modern CPUs utilize a 'Pipeline' to execute multiple instructions simultaneously. When the CPU hits an if statement, it doesn't know which path to take, so it guesses (Branch Prediction) to keep the pipeline full. If it guesses wrong (a Branch Misprediction), it must flush the entire pipeline and start over, losing 10-20 CPU cycles. Sorting an array before looping through it with an if statement can make the code run 3x faster because it makes the branch highly predictable!

Real-World Example

Validating user input boundaries securely to prevent crashes before executing business logic.

example
cpp
#include <iostream>

int main() {
    int age;
    std::cout << "Enter age: ";
    std::cin >> age;
    
    // Guard Clause: Instantly reject invalid data
    if (age < 0 || age > 120) {
        std::cout << "Error: Invalid age.\n";
        return 1; // Terminate early
    } 
    
    if (age >= 18) {
        std::cout << "Access granted to adult restricted area.\n";
    } else {
        std::cout << "Access denied.\n";
    }
    
    return 0;
}

Check Your Knowledge

Test your understanding of If...Else with these quick questions.

Question 1

What is the result of executing the following C++ code? `bool isAdmin = false; if (isAdmin = true) { cout << "Welcome"; }`

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++

If...Else

Overview

Programs are useless if they execute the exact same instructions every time they run. They need the ability to make decisions based on dynamic variables. The if...else statement is the fundamental building block of logic in C++.

It evaluates a boolean expression (a statement that resolves to true or false). If the condition is true, it executes the block of code inside the curly braces. If false, it completely ignores that block and moves on to the else block. In highly optimized, performance-critical C++ applications (like Unreal Engine), developers must be incredibly careful with complex if statements due to a hardware concept called 'Branch Prediction', where the CPU tries to guess which path the if statement will take to save time.

Syntax

cpp
int score = 85;

// 1. Basic If-Else
if (score >= 90) {
    std::cout << "Grade: A\n";
} 
// 2. Chained Conditions
else if (score >= 80) {
    std::cout << "Grade: B\n";
} 
// 3. Fallback
else {
    std::cout << "Grade: C or lower\n";
}

Common Pitfalls

  • The Assignment vs. Equality bug. Writing if (score = 100) is a catastrophic logic error. The single = is an assignment operator. It physically changes the score to 100, which evaluates to true, meaning the 'If' block will always execute! You MUST use the double == for equality checking: if (score == 100).
  • Omitting the curly braces {}. If you write an if statement without curly braces, C++ will only apply the condition to the very first line of code beneath it. The second line will execute unconditionally, leading to incredibly confusing bugs.

Interview Questions

Explain what 'Branch Prediction' is and why highly unpredictable if statements inside massive loops slow down C++ programs.

Modern CPUs utilize a 'Pipeline' to execute multiple instructions simultaneously. When the CPU hits an if statement, it doesn't know which path to take, so it guesses (Branch Prediction) to keep the pipeline full. If it guesses wrong (a Branch Misprediction), it must flush the entire pipeline and start over, losing 10-20 CPU cycles. Sorting an array before looping through it with an if statement can make the code run 3x faster because it makes the branch highly predictable!

Real-World Example

Validating user input boundaries securely to prevent crashes before executing business logic.

example
cpp
#include <iostream>

int main() {
    int age;
    std::cout << "Enter age: ";
    std::cin >> age;
    
    // Guard Clause: Instantly reject invalid data
    if (age < 0 || age > 120) {
        std::cout << "Error: Invalid age.\n";
        return 1; // Terminate early
    } 
    
    if (age >= 18) {
        std::cout << "Access granted to adult restricted area.\n";
    } else {
        std::cout << "Access denied.\n";
    }
    
    return 0;
}

Check Your Knowledge

Test your understanding of If...Else with these quick questions.

Question 1

What is the result of executing the following C++ code? `bool isAdmin = false; if (isAdmin = true) { cout << "Welcome"; }`

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