order of subexpression evaluation

M

mario semo

Hello,

evaluating

(foo(bar(100.0))) / (foo(bar(10.0)))

i would expect

calculate foo(bar(100.0)
calculate foo(bar(10.0)
divide
(or maybe foo(bar(10));foo(bar(100));reversed divide;)

but i have a compiler which splits the foo/bar calls to:
reg1=bar(100.0)
reg2=bar(10.0)
foo(reg1)
foo(reg2)
divide

this yields incorrect results in the following sample :

double * bar(double d)
{
static double _sd;
_sd = d;
return &_sd;
}

double foo(double *d)
{
return *d;
}

(the result of 100/10 is 1.)

is this allowed order of subexpr.evaluation or a compiler bug?

Note : some compiler behave different whether foo is a function or a macro:

#define foo(d) (*(d))
 
A

Alf P. Steinbach

* mario semo:
evaluating

(foo(bar(100.0))) / (foo(bar(10.0)))

i would expect

calculate foo(bar(100.0)
calculate foo(bar(10.0)
divide
(or maybe foo(bar(10));foo(bar(100));reversed divide;)

The compiler is free to evaluate the subexpressions in any order,
subject to the constraint that a function's arguments must necessarily
all be evaluated before actually calling that function.
 
F

Flo

Hello

If you google for c++ and sequence points you find information on how
the c++ compiler has to evaluate the syntax tree ("sub-expression
tree"): What he is free to do and where it is restricted by some rules.

In short and not very exact: Sub-expressions can be evaluated in any
order. However at sequence points, everything must be done. I.e. all
side effects must be completed. Sequence points are for example the
operators ; && || ?: , function call

Your compiler behaves correctly. The only thing he has to do is
- evaluate 100.0 before calling bar with it as argument
- evaluate 10.0 before calling bar with it as argument
- evaluate bar(100.0) before calling foo with it as argument
- evaluate bar(10.0) before calling foo with it as argument

This 4 rules leave the compiler quite a lot of freedom in which order
it evaluates all the sub expressions.

A side which goes into the details:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n926.htm

Greetings

Flo
 

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,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top