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 ofnum
by 1 before its current value is used.int pre_increment = ++num;
:num
is first incremented to 6, then assigned topre_increment
.cout << "Pre-increment: " << pre_increment << endl;
: Outputs the value ofpre_increment
, which is 6.cout << "Num after pre-increment: " << num << endl;
: Outputs the value ofnum
after pre-increment, which is also 6.Post-increment (++):
num++
: Uses the current value ofnum
and then incrementsnum
by 1.int post_increment = num++;
: The current value ofnum
(5) is assigned topost_increment
, thennum
is incremented to 6.cout << "Post-increment: " << post_increment << endl;
: Outputs the value ofpost_increment
, which is 5 (the value before incrementing).cout << "Num after post-increment: " << num << endl;
: Outputs the value ofnum
after post-increment, which is 6.