When doing something like this:
i2 = i++;
The ++
operator will return i
, and then it will increment i
by one.
Can a function also return something and then execute its code?
When doing something like this:
i2 = i++;
The ++
operator will return i
, and then it will increment i
by one.
Can a function also return something and then execute its code?
No, once the scope of a function is over (at the closing }
), no further code can be executed.
However, the function can store the old state of the input, modify the input, and return the old value of the input. This gives the effect of executing code after the function returns a value. As an example:
int f(int &n) {
int x = n; // store input
n = 42; // input is modified before return
return x; // old input is returned
}
int b = f(a); // b is equal to a
// but now a is 42
As you have observed, post-increment is an example of where such behavior is useful. Another example would be std::exchange
, which gives the appearance of modifying the input after returning a value.
If you were to implement postfix increment by yourself, you would first store the original value, then use increment but still return the original value:
Number Number::operator++ (int)
{
Number ans = *this;
++(*this);
return ans;
}
You may check this FAQ for more details: https://isocpp.org/wiki/faq/operator-overloading#increment-pre-post-overloading
So there is no function code execution after return in C++
.