Hi I am currently learning about operators and I am confused on the actual use of the incremental operator ++
What I know thus far is
-when its a prefix incremental operator the value returned is the value in the counter after it has been incremented.
-when its a postfix incremental operator the value returned is the value in the counter before it has been incremented.
So with code I have the following to try to see it in action
//Header files
#include "stdafx.h"
#include <iostream>
usingnamespace std;
int main()
{
//variables declared
int a = 1;
int b;
int c;
b = ++a; //passing value of 2 to b
c = a++; //passing value of 1 to c
cout << b << endl; //output is 2
cout << c << endl; //output is 2
cin.get();
return 0;
}
So my question is the following, I understand why the printout is 2 for my b variable but for my c variable its also a 2? I thought it passed the value in variable a first giving me an output of 1?
I am very new only programming couple days, any help in understanding this would be appreciated.
a = 1;
// here, a is 1
b = ++a; // a is incremented (a=2) then assigned to b (b=2)
// here, a is 2
c = a++; // a is assigned to c (c=2) then a is incremented (a=3)
// here, a is 3
/*
End result:
a = 3
b = 2
c = 2
*/
a = 1;
b = ++a; //a is incremented to 2 then returned
c = a++; //a is still 2 (from the last statement), a makes a copy of itself (2)
//and then increments itself to 3, but the copy is returned from the operator (2)