Note details

Increment and Decrement Operators in C++

BY a4gqz
August 23, 2025
Public
Private
7080 views

Lecture Notes: Increment and Decrement Operators in C++

Introduction

Welcome to the lecture on increment and decrement operators in C++. We'll cover the following topics:

  • Pre-increment and pre-decrement operators
  • Post-increment and post-decrement operators
  • Side effects associated with these operators in C++

Pre-Increment and Pre-Decrement Operators

  • Purpose: Increment or decrement a value by one.
  • Syntax: ++x (increment), --x (decrement)
  • Functionality:
    • Increment/decrement occurs before returning the updated value.
    • Unary operators applied before the operand.
  • Example:
    • Variable val initialized to 4.
    • ++val results in 5 (increment happens first).
    • --val on updated val results in 4.

Post-Increment and Post-Decrement Operators

  • Purpose: Increment or decrement a value by one.
  • Syntax: x++ (increment), x-- (decrement)
  • Functionality:
    • A copy of the value is created, the original is incremented/decremented, and the copy is returned.
    • Operators applied after the operand.
  • Example:
    • Variable val initialized to 4.
    • val++ returns 4, but val becomes 5.
    • val-- returns 5, but val becomes 4.

Side Effects

  • Definition: An operator causing additional actions beyond returning a value.
  • Examples:
    • Assignment operator (=) assigns and returns the value.
    • Pre-increment (++x) updates and then returns the value.
  • Avoid Pitfalls:
    • Do not update and use a variable with side effects in the same line (++val + val).
    • Leads to undefined behavior; the order of operation is compiler-dependent.

Conclusion

  • Practice caution with operators that have side effects to avoid undefined behavior.
  • Always separate updates and uses of the same variable to ensure predictable outcomes.

Thank you for attending the lecture. See you in the next one!