By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,413 Members | 996 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,413 IT Pros & Developers. It's quick & easy.

is it undefined behaviour?

P: n/a
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
Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
> x.foo(a).foo(b).foo(c); // 2

should be

x.foo(a * b).foo(b * c).foo((a = 0, b = 0));
Jul 23 '05 #2

P: n/a
"Daniel Schüle" <uv**@rz.uni-karlsruhe.de> wrote...
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
Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.