Given the following code, will ixAdd do what you'd expect, i. e. return the value of ix before the increment, but increment the class member before leaving the function?
class myCounter {
private int _ix = 1;
public int ixAdd()
{
return _ix++;
}
}
I wasn't quite sure if the usual rules for post / pre increment would also apply in return statements, when the program leaves the stack frame (or whatever it is in Java) of the function.
a++ returns the value of a before it was incremented. Show activity on this post. From the java doc: The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value.
The post increment operator is used to increment the value of some variable after using it in an expression. In the post increment the value is used inside the expression, then incremented by one. if the expression is a = b++; and b is holding 5 at first, then a will also hold 5.
What is Postfix Operator in Java. In Postfix increment, the ++ operator appears after the variable, i.e., “i ++”. The post-increment operator first, returns the variable's original value, and afterward, increments the variable's value by 1.
2) Post-increment operator: A post-increment operator is used to increment the value of the variable after executing the expression completely in which post-increment is used. In the Post-Increment, value is first used in an expression and then incremented. Syntax: a = x++;
The key part is that a post increment/decrement happens immediately after the expression is evaluated. Not only does it happen before the return occurs - it happens before any later expressions are evaluated. For instance, suppose you wrote:
class myCounter {
private int _ix = 1;
public int ixAdd()
{
return _ix++ + giveMeZero();
}
public int giveMeZero()
{
System.out.println(_ix);
return 0;
}
}
That would print out the incremented result as well, because the increment happens before giveMeZero()
is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With