Help with prefix and postfiix | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

5th Jun 2017, 4:50 AM
EmeraldHarp
EmeraldHarp - avatar
5 Answers
+ 6
prefix = do (fix) the sum before (pre) we do the code postfix = do (fix) the sum after (post) we do the code
5th Jun 2017, 5:17 AM
jay
jay - avatar
+ 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!
5th Jun 2017, 5:22 AM
Rrestoring faith
Rrestoring faith - avatar
+ 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.
5th Jun 2017, 5:54 AM
Dragon Slayer Xavier
Dragon Slayer Xavier - avatar
+ 4
@rRestoring: Just wow. Champ badge unlocked
5th Jun 2017, 5:26 AM
jay
jay - avatar
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.
5th Jun 2017, 5:34 AM
EmeraldHarp
EmeraldHarp - avatar