Is the behavior of return x++; defined?

别说谁变了你拦得住时间么 提交于 2019-12-03 09:45:34

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.

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.

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.

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

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!