Re: order of operations question
On 13 Sep., 23:59, allag...@gmail.com wrote:
Say you have this line of code:
m << f() << g();
We know the results of f() will be serialized before the results of
g(). But f is not guaranteed to be executed before g, right?
It is correct, that the order of evaluation of f() and g() is
unspecified, because these are subexpressions. The new nomenclature
of the C++ standard is, that f() and g() are unsequenced (This
renaming has been done to include the upcoming multi-threading
awareness of C++ into this behaviour).
This straightforward question has provoked some debate at work. One
guy states this is equivalent to this example from section 6.2.2 of
Stroustrup's "The C++ Programming Language" (2nd ed.):
int x = f(2) + g(3); // undefined whether f() or g() is called first
Yes, this is a very similar example.
Another contends that since you can write the example as:
(m.operator<<(f())).operator<<(g());
that f must be executed before g.
The above conclusion is wrong. The order of evaluation
is here also unspecified, independent on the number or
position of parentheses. The above exanded version is btw.
also equivalent to the simpler form
m.operator<<(f()).operator<<(g());
but that is not relevant in the discussion, because the
compiler can chose either of the following invokation orders:
[A]:
1) f()
2) g()
3) << (left one)
4) << (right one)
[B]:
1) g()
2) f()
3) << (left one)
4) << (right one)
Note that compiler *cannot* change the order of the <<
operations, because the result of the first is input
of the second. For the same reasons do chained expression
in C have a sequenced order, e.g. the combination of
str* functions (which always return cv char*), like this:
const char src* = ... ;
char dst[] = ...;
strrchr(strchr(strcat(strcpy(dst, src), strstr("Huhu", "u")), '.'),
'-');
You will find that in the above example also exists
one degree of freedom: strcpy(dst, src) and strstr("Huhu", "u")
are both unsequenced. This does not harm in this example,
but you can think of similar problematic situations
as described in your original question.
There exists only a very limited set of operations in
C++ which a sequenced order of evaluation of
subexpressions, e.g. the 'operator,', operator?,
and the built-in versions of && and ||.
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]