is it undefined behaviour?

  • Thread starter =?ISO-8859-1?Q?Daniel_Sch=FCle?=
  • Start date
?

=?ISO-8859-1?Q?Daniel_Sch=FCle?=

Hi all!

given the following code

#include <iostream>

using std::cout;
using std::endl;

struct X
{
X & foo(int x){ cout << x << endl; return *this; }
};

void bad(int x, int y)
{
cout << x << '\t' << y << endl;
}

int main()
{
int a = 1, b = 2, c = 3; // 1
cout.operator <<(a * b).operator <<(b * c).operator <<((a = 0, c = 0));

a = 1, b = 2, c = 3;
X x;
x.foo(a).foo(b).foo(c); // 2

a = 1, b = 2;
bad(a * b, a=0); // 3

return 0;
}

Is it safe to assume that 1 and 2 will produce on every C++
implementation the same output (no undefined behaviour here)?
Or may C++ Compiler compute all the values in () first (as it may do in
bad), and then invoke function foo?

thx in advance

-Daniel
 
?

=?ISO-8859-1?Q?Daniel_Sch=FCle?=

x.foo(a).foo(b).foo(c); // 2

should be

x.foo(a * b).foo(b * c).foo((a = 0, b = 0));
 
V

Victor Bazarov

Daniel Schüle said:
given the following code

#include <iostream>

using std::cout;
using std::endl;

struct X
{
X & foo(int x){ cout << x << endl; return *this; }
};

void bad(int x, int y)
{
cout << x << '\t' << y << endl;
}

int main()
{
int a = 1, b = 2, c = 3; // 1
cout.operator <<(a * b).operator <<(b * c).operator <<((a = 0, c = 0));
a = 1, b = 2, c = 3;
X x;
x.foo(a * b).foo(b * c).foo((a = 0, b = 0)); // 2

a = 1, b = 2;
bad(a * b, a=0); // 3

return 0;
}

Is it safe to assume that 1 and 2 will produce on every C++ implementation
the same output (no undefined behaviour here)?

Actually, no. There is no undefined behaviour, simply unspecified order
of evaluation. The order of evaluating subexpressions is only specified
for the comma operator, the ternary operator, and the logical operators.
The rest is up to the compiler (see 5/4). The expression

x.foo(blah).foo(blahblah)

contains essentially this:

typeof<x>::foo(typeof<x>::foo(x, blah), blahblah)

as you can see the order of evaluating blahblah and the first 'foo' is
unspecified. You can extend it more I am sure.

Actually, let me take "no undefined behaviour" back. In all of these
expressions the values of 'a' are both set and accessed between sequence
points, so, yes, undefined behaviour takes place.
Or may C++ Compiler compute all the values in () first (as it may do in
bad), and then invoke function foo?

That's right. You can only say that in the subexpression (a = 0, c = 0)
'a' will be assigned 0 first, then c will be assigned 0.

V
 

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

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top