+ 5

Hello every one 😊 can you please tell me what is the difference between n++ and n=n++ and n=n+1 ?? In c++

18th Feb 2017, 5:14 PM
oi_io
10 Respostas
+ 7
thank you all for answering 😊 actually i replaced n=n+1 with n=n++ in a while loop and it printed infinit numbers so i was confused but i think i am understanding now thanks for helping 👍😊
18th Feb 2017, 5:33 PM
oi_io
+ 5
this is the problem👇 int main() { int n=1; while(n<6) { cout<<n<<endl; n++; } } this program prints 👇 1 2 3 4 5 but when i replace the n++ with n=n++ it printed 👇 1 1 1 1 1 1 forever
18th Feb 2017, 5:46 PM
oi_io
+ 3
Don't do things like n = n++; n++ is the same as n = n + 1, so by using n = n++ you change n twice in the same line which can get you really unpredictable results!
18th Feb 2017, 5:23 PM
Robobrine
Robobrine - avatar
+ 2
the output will be different when using something like cout<<(n=n+1); just replace the expression in parentheses by n=n++ and n++ make sure to set n=0 before.
18th Feb 2017, 5:31 PM
Mario L.
Mario L. - avatar
+ 2
n++ is a post_increment operation whose value can only be updated when u go to the next statement n=n+1 is a normal arithmetic operation n+=1 and ++n have same meaning they update themselves on the spot.
18th Feb 2017, 6:28 PM
Purna Chandra Pradhan
Purna Chandra Pradhan - avatar
+ 2
n++ and n=n+1 are the same. n++ - it use plus after iteration ++n - it use plus before iteration so it may be n-- or --n
1st Mar 2017, 4:15 PM
НоĐșота ĐšŃ€Đ”ĐŒĐœŃ‘ĐČ
НоĐșота ĐšŃ€Đ”ĐŒĐœŃ‘ĐČ - avatar
+ 1
@王文琊 (and also @Moksh Makhija) n = n++; is not the same as n = n; n++; (or just: n++) It's more like n++; n = n - 1; (or: n = (n = n + 1) - 1;) So in the end n doesn't change. (n = n;)
18th Feb 2017, 5:47 PM
Robobrine
Robobrine - avatar
+ 1
Yes, n = n++; doesn't change n (it's like writing n = n;), so the loop will get stuck with n=1 and therefor never end.
18th Feb 2017, 5:50 PM
Robobrine
Robobrine - avatar
0
n++ and n=n+1 are same meaning. n=n++ can be divided into{ n=n; n++; }
18th Feb 2017, 5:23 PM
王文琊
王文琊 - avatar