+ 2
Im a beginner for C++ . Can u guys tell me a easy way to understand ++x and x++?
Basic C++
10 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
+ 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.
+ 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.
+ 1
Umar Sunusi Maitalata can u explain with an example? Thanks
+ 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..
0
Umar Sunusi Maitalata can u explain bit more about x++? Its bit confusing!
0
Refer to the below link :
https://www.sololearn.com/learn/CPlusPlus/1610/?ref=app
Also, check page 5 & 6 here
0
++x increases 1 and then evaluates while ++x evaluates first and then increments 1