pre increment vs post increment c++

#include <iostream>
using namespace std;

int main() {
    int num = 5;

    // Pre-increment
    int pre_increment = ++num;
    cout << "Pre-increment: " << pre_increment << endl; // Output: 6
    cout << "Num after pre-increment: " << num << endl; // Output: 6

    num = 5; // Reset num

    // Post-increment
    int post_increment = num++;
    cout << "Post-increment: " << post_increment << endl; // Output: 5
    cout << "Num after post-increment: " << num << endl; // Output: 6

    return 0;
}

Explanation:

  • Pre-increment (++):
  • ++num: Increments the value of num by 1 before its current value is used.
  • int pre_increment = ++num;: num is first incremented to 6, then assigned to pre_increment.
  • cout << "Pre-increment: " << pre_increment << endl;: Outputs the value of pre_increment, which is 6.
  • cout << "Num after pre-increment: " << num << endl;: Outputs the value of num after pre-increment, which is also 6.

  • Post-increment (++):

  • num++: Uses the current value of num and then increments num by 1.
  • int post_increment = num++;: The current value of num (5) is assigned to post_increment, then num is incremented to 6.
  • cout << "Post-increment: " << post_increment << endl;: Outputs the value of post_increment, which is 5 (the value before incrementing).
  • cout << "Num after post-increment: " << num << endl;: Outputs the value of num after post-increment, which is 6.