If I have for example a class with instance method and variables
class Foo
{
...
int x;
int bar() { return x++; }
};
Is the behavior of returning a post-incremented variable defined?
If I have for example a class with instance method and variables
class Foo
{
...
int x;
int bar() { return x++; }
};
Is the behavior of returning a post-incremented variable defined?
Yes it is ... it will return the x's value before incrementing it and after that the value of x will be + 1 ... if it matters.
It is defined.
It returns the value of x
before incrementation. If x
is a local(non-static) variable this post incrementation has no effect since local variables of a function cease to exist once the function returns. But if x
is a local static variable, global variable or an instance variable( as in your case), its value will be incremented after return.
Yes, it's equivalent to:
int bar()
{
int temp = x;
++x;
return temp;
}
Most programming languages, like C++, are recursive in the order that operations are carried out (I'm not making any implication about how the code is actually implemented by the compiler here). Compound operations that are composed of any well defined operations are themselves well defined, since each operation is carried out on a last-in, first-out basis.
Post-increment returns the value of the variable being incremented before incrementing it, so the return
operation recieves that value. No special definition of this behavior has to be made.