+ 4
Can someone plz make it more clear about x++ and ++x ?
what's the main difference between these two ? plz make it more clear
7 Answers
+ 4
@neetish raj
In example you gave the output of y is coming 13 not 12. You can give it a try on code playground. Hope you make it clear and then post it.
+ 2
x++ is post increment operator
and
++x is pre incremental operator
+ 2
when u encounter ++x, first increase x value with 1 then do any operations on that statement . hence called pre increment.
when u encounter x++, first perform operations on that statement for x without bothering about increment but after that statement x value will be increment by 1. hence post increment
example: x=5;
y=++x + x++;
y will be 12 as y=6 + 6
but after this statement x becomes 7
now answer this
int x=6;
int y=++x - x++ + ++x;
cout<<y;
cout<<x;
+ 1
@neetish raj
I referred to one of my books for the answer and found that this is compiler dependent and should not be used (multiple increment /decrement).
0
@ Rishav agarwal, thx for pointing out this SoloLearn compiler error, it made my head scratch too much,
I don't know why but SoloLearn s compiler does error here, where as the same code in my PC code blocks gives. 12, and Linux too.
but the SoloLearn compiler is giving 13 (code is shared with name test).
guyz u can check that out, with ur PC compiler s, so as far as I can tell my explanation is correct and example s too. but open to suggestions
0
@rishabh
@neetish
I am having same doubt. This type of question has been asked in challenges and that's why I was doing it wrong all the time.
- 2
nefore posting u must look if this question was asked before.
u will get instant answer