x=x++ -- undefined behaviour?

K

kwikius

Is the marked section in main so-called "undefined behaviour".

struct value_type{
value_type (): v(0){}
value_type & operator = ( value_type const & in)
{
v = in.v;
return *this;
}
int v;
};

inline
value_type operator++(value_type & x,int)
{
value_type t = x;
++x.v;
return t;
}

int main()
{
value_type x;
//####################
x = x++; // undefined behaviour ??
//###############
x = (x++);
(x = x)++;
}

IMO it aint where x is a UDT with overloaded post operator ++.

But maybe I'm wrong?...

regards
Andy Little
 
E

Erik Wikström

Is the marked section in main so-called "undefined behaviour".

struct value_type{
value_type (): v(0){}
value_type & operator = ( value_type const & in)
{
v = in.v;
return *this;
}
int v;
};

inline
value_type operator++(value_type & x,int)
{
value_type t = x;
++x.v;
return t;
}

int main()
{
value_type x;
//####################
x = x++; // undefined behaviour ??
//###############
x = (x++);
(x = x)++;
}

IMO it aint where x is a UDT with overloaded post operator ++.

But maybe I'm wrong?...

No, it is well-defined, since x++ in this case is just syntactic sugar
for x.operator++(). The standard says that there is a sequence point
before copying the return value, so all side-effects of the function
must be done before the assignment.
 
A

Alf P. Steinbach

* kwikius:
Is the marked section in main so-called "undefined behaviour".

struct value_type{
value_type (): v(0){}
value_type & operator = ( value_type const & in)
{
v = in.v;
return *this;
}
int v;
};

inline
value_type operator++(value_type & x,int)
{
value_type t = x;
++x.v;
return t;
}

int main()
{
value_type x;
//####################
x = x++; // undefined behaviour ??
//###############
x = (x++);
(x = x)++;
}

IMO it aint where x is a UDT with overloaded post operator ++.

But maybe I'm wrong?...

Except for the zero, which I'm too lazy to look up whether it's required
to be zero or whatever, the expression is evaluated as

x.operator=( operator++( x, 0 ) );

These function calls introduce sequence points, in particular, there is
a sequence point between evaluating the argument to operator= and
executing the operator= function body, so that all side effects must be
complete.

So the behavior is not undefined.


Cheers, & hth.,

- Alf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,117
Latest member
Matilda564
Top