0
Increment operator confusion
I understand the concept of a prefix, but the more I go through the basic concept of postfix the more confused i am. I know ex 1.) x = 9; y = ++x // x is 10, y is 10 But post postfix doesn’t make sense y=x++ Am I assigning the value of x to y, then incrementing by 1. I don’t really understand this simple concept
3 odpowiedzi
+ 4
y = x++
Simply means "Assign x to the variable y, then increase x by 1 ".
Note, it's called "postfix" because the incrementation is done after the assignment.
y = x++
is the same as
y = x
x += 1
+ 1
It is exactly that. Postfix means that the other operation is done first, and the incrementation is done afterwards.
It is equivalent to writing y=x; x=x+1;
Most of the times, you can use one or the other, just having in mind the difference and adjusting your code the right way (for example if assigning a value or making a comparison, you should always be able to use both indifferently, admittedly with slight changes between the prefix and postfix version).
But sometimes it can be tricky, and mostly in case of errors and unexpected behavior of a program during the increment operation : in that case, the postfix and prefix implementation result in a different value for the variable (in one case incremented and in the other case not). And that may be all but trivial in some programs.
+ 1
thanks for the responses y’all!