3

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?

user8240761
  • 975
  • 1
  • 10
  • 15
  • 6
    No. `i++` stores the old value, then executes its code (increment), and then returns the stored value. – AndyG Jun 30 '20 at 13:06
  • 1
    In what practical situation would this be useful? – Guy Incognito Jun 30 '20 at 13:07
  • 2
    If `i` is an `int`, `i++` does not **return** anything. It's not a function. It's an **expression**, and its value is the old value of `i`. Expressions **have** values; functions **return** values. They're not the same thing. When a function returns it's finished; there's nothing more it can do. – Pete Becker Jun 30 '20 at 13:11
  • 1
    You can look at this [question](https://stackoverflow.com/questions/2380803/is-the-behavior-of-return-x-defined) where users discuss the use of `return i++` expression. Some of the answers point out that the compiler generates longer code anyway as if you wrote `int result = i; ++i; return result;`. So it doesn't really matter. – sanitizedUser Jun 30 '20 at 13:13
  • 1
    Show us *what* you want to do as opposed to *how* you want to do it. – Aykhan Hagverdili Jun 30 '20 at 13:15
  • @PeteBecker I like your explanation, please consider posting it as an answer – Marsroverr Jun 30 '20 at 13:16
  • When exactly do you expect "its code" to get executed, in relation to the code of wherever this function was called from? – Sam Varshavchik Jun 30 '20 at 13:16
  • Would multi threading count? – bey Jun 30 '20 at 13:33

2 Answers2

2

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.

cigien
  • 57,834
  • 11
  • 73
  • 112
0

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++.

Roman2452809
  • 378
  • 1
  • 2
  • 17