开发者

Is the behavior of return x++; defined?

开发者 https://www.devze.com 2022-12-21 19:19 出处:网络
If I have for example a class with instance method and variables class Foo { ... int x; int bar() { return x++; }

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-i开发者_如何学Cncremented variable defined?


Yes, it's equivalent to:

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


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.

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.


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.


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)
{
    int temp = *n;
    *n = *n + 1;
    return temp;
}


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号