Is the behavior of return x++; defined?

2020-06-07 05:15发布

问题:

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?

回答1:

Yes, it's equivalent to:

int bar()
{
  int temp = x;
  ++x;
  return temp;
}


回答2:

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.



回答3:

Yes.

In postincrement (x++) the value of x is evaluated (returned in your case) before 1 is added.

In preincrement (++x) the value of x is evaluated after 1 is added.

Edit: You can compare the definition of pre and post increment in the links.



回答4:

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.



回答5:

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.



回答6:

I think it is defined but not preferred. It causes confusion to people. For example, the following code prints 1 instead of 2.

#include <iostream>
#include <cstdlib>

using namespace std;

int foo()
{
    int i = 1;
    return i++;
}

int main()
{
    cout << foo() << endl;

    return 0;
}


回答7:

I know this question is answered long before but here's why it is defined. Compound operators are basically syntax sugar for functions. If you're wondering how the increment happens after returning from the function, it doesn't. It happens just before the operator "function" returns the previous value.

For an integer, think of the post increment operator function defined like this:

int post_increment(int *n)
{
    temp = *n;
    *n = *n + 1;
    return temp;
}