0
Help with prefix and postfiix
I have read many Q&A's about prefix and postfix but cant seem to understand. Can someone explain it in a way other than just variables, like with real world objects, if that's possible?
5 Réponses
+ 6
prefix = do (fix) the sum before (pre) we do the code
postfix = do (fix) the sum after (post) we do the code
+ 6
Prefix first increments then uses.
I have a number. This number is how many apple I have.
I have a function that accepts an int in it's arguments.
This function will make me throw x apples at a wall. x being the number passes in the argument.
Lets say I have 3 apples
Before I want to throw apples at a wall I want one more apple. I simply don't have enough apples!
So, I use prefix.
I increment my number of apples before throwing them.
increment: I go grab another apple. Now I have 4!
Use: I now throw the apples at the wall!
Now I am throwing 4 apples.
I no longer have any apples, and threw 4!
Lets say we have the 3 apples just like before, but now I want to use postfix.
Afterall, 3 is plenty, but when I'm done I want another for good luck.
Postfix: first uses then increments.
Use: I first throw my 3 apples.
Increment: I'm done throwing my apples. Now, I go and grab another.
Now I still have an apple!
+ 5
Let's give an example.
Postfix:
int x=3, y=4;
//For putting the value of x in y and incrementing x without using postfix.
y=x;
++x;
System.out.println(x);
System.out.println(y);
/*Output
3
4*/
//Using postfix
int x=3, y=4;
y=x++;
System.out.println(x);
System.out.println(y);
//Same output
Prefix:
int x=3,y=4;
//For putting the incremented value of x in y and incrementing x also without prefix
x++
y=x;
System.out.println(x);
System.out.println(y);
/*Output
4
4*/
//Using prefix
int x=3,y=4;
y=++x;
System.out.println(x);
System.out.println(y);
//Same output
So consistent use of prefix and postfix decreases the number of lines in a code and makes it easy to maintain.
+ 4
@rRestoring: Just wow. Champ badge unlocked
0
@Restoring faith: So now that I understand it a bit more, the next question is what purpose would this ever have in programming? Its seems useless to me.