+ 2

Can someone explain me prefix and postfix

How in postfix the value is used first and then it is incremented or decremented

27th May 2017, 9:50 AM
Vishal Shivnani
Vishal Shivnani - avatar
4 Réponses
+ 5
preincrement b = ++a; => b = (++a); postincrement b = a++; => (b = a); a++;
27th May 2017, 9:58 AM
Emore Anzolin
Emore Anzolin - avatar
+ 4
Furthermore, in C++ (it is very likely the same in Java), the postfix incremental x++ invokes the copy constructor of the integer "class", effectively resulting in an overhead when you simply want an increment of your variable. This becomes important and more dramatic when you call this incremental multiple times as in the head of a for-loop or in the Body of a loop. ++x does not invoke the copy constructor and increments "right away". You should always prefer this unless the post - incremental is exactly what you need for the logic of your algorithm.
28th May 2017, 9:54 AM
MMK
MMK - avatar
+ 1
Really simple: - prefix evaluates the expression and returns the updated value back. - postfix first returns the value and then evaluates the expression. Example: int x_prefix = 0; int x_postfix = 0; System.out.println(++x_prefix); // result: 1 System.out.println(x_prefix); // result: 1 System.out.println(x_postfix++); // result: 0 System.out.println(x_postfix); // result: 1 Hope that helps. :)
27th May 2017, 9:56 AM
Thanh Le
Thanh Le - avatar
+ 1
//Description about postfix and prefix ++ has higher precedence than arithmetic operators ++/-- has two types (postfix or prefix) if it is postfix: only value will be assigned to 'b' and after execution of current instruction postfix operator give operation effect if it is prefix: only associated operator with prefix operator will increment and value will be assigned to b example: a=5; b=a++; //value of b will be 5, after execution of this statement, a will increment by 1 a=5; b=++a; //first value of a will increment by a and then value will be assign to b value of a and b will be 6, 6 respectively.
27th May 2017, 10:15 AM
Kamlesh Patel
Kamlesh Patel - avatar