0

why this output 2 not 3 ? #include <iostream> using namespace std; int main() { int x=1; x=x++; cout<<++x; }

25th Aug 2016, 12:33 PM
Lekhraj Singh
Lekhraj Singh - avatar
5 Antworten
+ 2
@Josyah: The second part is not really true. Anyways the code is executed in the following order: 1. x is set to 1 (x=1) 2. the value of x is incremented to 2 (x++) 3. a temporary variable with the xs original value of 1 is returned (x++) 4. x is assigned the temporary variable that is 1 (x=) 5. x is incremented to 2 (++x) 6. the value of x is returned (++x) 7. the value is outputted (cout <<)
25th Aug 2016, 8:49 PM
Stefan
Stefan - avatar
0
x = x++ is the same as just putting x++. And cout << ++x is printing x before it is iterated once more
25th Aug 2016, 12:48 PM
Josyah Dooley
Josyah Dooley - avatar
0
Yes, your correct. I had them backwards not paying attention. Thanks for point that out, i dont use ++val that often
25th Aug 2016, 9:24 PM
Josyah Dooley
Josyah Dooley - avatar
0
@Josyah: No prob, I rectified an ordering mistake that did not have any influence on the outcome and hopefully improved the formulation.
25th Aug 2016, 10:00 PM
Stefan
Stefan - avatar
0
thanks Stefan
26th Aug 2016, 3:58 AM
Lekhraj Singh
Lekhraj Singh - avatar