Topic: interleaved evaluation of function argumen


Author: clamage@taumet.eng.sun.com (Steve Clamage)
Date: 1996/09/24
Raw View
In article 44D8@kodak.com.au, Trevor Yann <ty@kodak.com.au> writes:
>Is there any restriction on the evaluation of function arguments that prevents
>interleaved evaluation?

No, but your question below involves another rule as well.

>
>e.g.
>
>int foo()
>{
> cout << '0';
> cout << '1';
> return 0;
>}
>
>int bar()
>{
> cout << 'A';
> cout << 'B';
> return 0;
>}
>
>void f(int, int);
>
>f(foo(), bar());
>
>The output is allowed to be 01AB and AB01, becuase there is no sequence point
>between the evaluation of foo() and bar().

Correct.

> Is the output also allowed to be 0AB1, 0A1B, A01B, A0B1?

No, because function calls are involved, and the execution of function
bodies cannot be interleaved. Draft section 1.3 "Program execution" makes
that point explicitly.

You don't know whether foo or bar will be called first, and you don't
know the order of evaluation of any arguments to foo and bar, but
you do know that whichever is called first must return before the
other is entered.

>If this is allowed, would parallel evaluation be allowed?

The draft does not directly address parallel evaluation. Instead, it
describes an abstract machine, sequence points, and allowable
sequences of execution. Whether or not parallelism is involved, an
implementation is valid if and only if the observable results correspond
to some allowed execution sequence of the abstract machine.

>Both interleaved and parallel evaluation of function arguments introduce problems
>with code that changes any global state, like global variables.

Yes, but that problem exists anyway. A program should not depend on
the order of side effects without explicit sequence points.
Your example can print "AB01" or "01AB", and I suppose you would care
which string was printed. To ensure one order or the other, you would
write something like this:

 int t1 = foo(); // sequence point at the semicolon
 int t2 = bar(); // always yields "01AB"
 f(t1, t2);

A more subtle example is when foo modifies a global variable which bar
reads. That kind of invisible coupling makes programs hard to maintain,
since seemingly trivial changes can yield incorrect results. So it is
even better to avoid the dependence on the order of side effects
entirely.
---
Steve Clamage, stephen.clamage@eng.sun.com




[ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]