+ 2

Im a beginner for C++ . Can u guys tell me a easy way to understand ++x and x++?

Basic C++

16th Feb 2019, 11:17 AM
Sandun Madush
Sandun Madush - avatar
9 Answers
+ 9
In any expression for ex: a=b+c++; or cout<<x++; In post increment, first the current value of the variable will be used in expression evaluation, then after the post increment expression is evaluated. Means for above examples, the compiler performs as a=b+c; c++; means c=c+1; cout<<x; x++; means x=x+1; if a=1,b=2,c=3, x=4 then, after executing above statements a=5, c=4 ; 4 printed on screen, then x incremented. In pre-increment ex: ++x, the value of x is incremented first, then it will be used. in above example if x=4, then cout<<++x; x is incremented first then printed on screen. then x=5, so 5 printed on screen. Edit: In c++, But if expression, contains multiple compound statements of pre or post increment statements, then result is may different in defferent compilers. Behaviour is undefined depending on standards. See in this for more information. https://en.m.wikipedia.org/wiki/Sequence_point & https://www.sololearn.com/Discuss/2038766/?ref=app
20th Apr 2019, 11:15 AM
Jayakrishna 🇼🇳
+ 5
Let's say your x is 1. If you write cout << ++x; The output will be 2 because x will be incremented first before it's printed on the console. However, if you were to write cout << x++; Then the output will be 1 because the statement (printing x) will execute first before your x will be incremented. After the statement is executed x becomes 2. I hope this help.
16th Feb 2019, 11:26 AM
Umar Sunusi Maitalata
Umar Sunusi Maitalata - avatar
+ 5
It's called post-increment. Anywhere you see x++, the statement that contains the x++ will execute first before the actual value of x is incremented.
16th Feb 2019, 11:32 AM
Umar Sunusi Maitalata
Umar Sunusi Maitalata - avatar
16th Feb 2019, 11:36 AM
Umar Sunusi Maitalata
Umar Sunusi Maitalata - avatar
+ 1
Umar Sunusi Maitalata can u explain with an example? Thanks
16th Feb 2019, 11:35 AM
Sandun Madush
Sandun Madush - avatar
+ 1
x++ means that the value of x is used first in the expression statement after that value incremented one and stored in x variable..
25th Jul 2019, 5:36 PM
Jayakrishna 🇼🇳
0
Umar Sunusi Maitalata can u explain bit more about x++? Its bit confusing!
16th Feb 2019, 11:29 AM
Sandun Madush
Sandun Madush - avatar
0
Refer to the below link : https://www.sololearn.com/learn/CPlusPlus/1610/?ref=app Also, check page 5 & 6 here
30th Apr 2019, 5:44 AM
Mohd Ashraf Shaikh
Mohd Ashraf Shaikh - avatar
0
++x increases 1 and then evaluates while ++x evaluates first and then increments 1
29th Nov 2020, 6:24 PM
Adnan Musa
Adnan Musa - avatar