Numbers

Pre vs Post Increment

Why does Level++ and ++Level do the same thing? When should I use one over the other?

3D art showing a character using an abacus

While Level++ and ++Level might appear to do the same thing when used alone, they actually behave differently when used within larger expressions. Let's explore the difference:

Basic Behavior

When used in isolation, both increment the variable by 1:

#include <iostream>
using namespace std;

int main() {
  int levelA{5};
  int levelB{5};

  ++levelA; // Pre-increment
  levelB++; // Post-increment

  cout << "levelA: " << levelA << "\n";
  cout << "levelB: " << levelB;
}
levelA: 6
levelB: 6

The Important Difference

The difference becomes apparent when you use them as part of a larger expression:

#include <iostream>

int main() {
  int level{5};

  // Level is incremented, then assigned
  int resultA{++level}; 
  std::cout << "Using ++level:\n";
  std::cout << "level: " << level << "\n";
  std::cout << "resultA: " << resultA << "\n\n";

  level = 5; // Reset level

  // Level is assigned, then incremented
  int resultB{level++}; 
  std::cout << "Using level++:\n";
  std::cout << "level: " << level << "\n";
  std::cout << "resultB: " << resultB;
}
Using ++level:
level: 6
resultA: 6

Using level++:
level: 6
resultB: 5

When to Use Each

Use pre-increment (++level) when:

  • You want the incremented value immediately in the same expression
  • You're writing performance-critical code (pre-increment can be slightly faster)

Use post-increment (level++) when:

  • You need the original value for something before incrementing
  • You're implementing a counter that should increment after its current value is used

Here's a practical example using a game loop:

#include <iostream>
using namespace std;

int main() {
  int turnNumber{1};
  int maxTurns{3};

  while (turnNumber <= maxTurns) {
    cout << "Processing turn " 
      << turnNumber++ << "\n"; 
  }
}
Processing turn 1
Processing turn 2
Processing turn 3

In this example, we use post-increment because we want to display the current turn number before incrementing it for the next iteration.

Answers to questions are automatically generated and may not have been reviewed.

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved