-4

I was working with my practicals and my tutor taught us the increment and decrement operators but I cannot understand a few things in code. The code is as follows :

#include < iostream >

using namespace std;

int main() {

    int a = 10 , b = 100 , result_a , result_b ;

    // Prefix Example

    // Printing the value given by increment Operator on A
    result_a = ++a;
    cout << "Prefix Increment A : " << result_a << endl;

    // Printing the value given by decrement Operator on B
    result_b = --b;
    cout << "Prefix Decrement B : " << result_b << endl;

    cout << a << endl << b << endl;

    // Postfix Example

    // Printing the value given by increment Operator on A
    result_a = a++;
    cout << "Postfix Increment A : " << result_a << endl;

    // Printing the value given by decrement Operator on B
    result_b = b--;
    cout << "Postfix Decrement B : " << result_b << endl;

    cout << a << endl << b << endl;
    cout << result_a << endl << result_b;
    
    system("pause>0");

    return 0;
}

And the output is as follows :

PS D:\Burhan\My coding projects\C++\WalletTerminal> if ( $? ) { g++ 
main.cpp -o main } ; if ( $? ) { .\main }
Prefix Increment A : 11
Prefix Decrement B : 99
11
99
Postfix Increment A : 11
Postfix Decrement B : 99
12
98
11
99

I don't understand why is the Postfix Increment A: 11 and Postfix Decrement B: 99 as my calculations say that it should be 12 and 98 which are the value of A and B. We are actually adding +1 to A and B but as far as I know, that happens after the line of code is executed but still, it doesn't work as intended. Can you please tell me how that works? I look on the internet but couldn't find any issues related to this.

Clifford
  • 88,407
  • 13
  • 85
  • 165

2 Answers2

1

You can look at it this way, when you use pre-increment or pre-decrement (++a, --b ) , what really happens is that for instance here

result_a = ++a; 

What really happens is,( since ++ is a short-hand operator for incrementing)

a=a+1;
result_a=a;

Similarly for post-increment or post-decrement (a++,b--)

result_b = b--;

what really happens is

result_b=b;
b=b-1;
Dhruva-404
  • 168
  • 2
  • 10
0

++a (Prefix) means firstly incrementing a and then using the value of a. a++ (Postfix) means firstly using the value of a and then incrementing a.

For example:

int a = 10;
std::cout << a++; // Will print out 10
// a == 11
int a = 10;
std::cout << ++a; // Will print out 11
// a == 11
The Coding Fox
  • 1,488
  • 1
  • 4
  • 18