patros
patros

Reputation: 7819

Is the behavior of return x++; defined?

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?

Upvotes: 33

Views: 28697

Answers (7)

Amal K
Amal K

Reputation: 4899

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

Upvotes: 3

Huiguorou
Huiguorou

Reputation: 397

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

Upvotes: 0

Andrew Noyes
Andrew Noyes

Reputation: 5298

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.

Upvotes: 2

Mizipzor
Mizipzor

Reputation: 52351

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.

Upvotes: 7

Peter Alexander
Peter Alexander

Reputation: 54270

Yes, it's equivalent to:

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

Upvotes: 63

codaddict
codaddict

Reputation: 455020

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.

Upvotes: 7

anthares
anthares

Reputation: 11213

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.

Upvotes: 13

Related Questions