[comp.std.c] order of evaluation & static variables

ado@sauna.hut.fi (Andre Dolenc) (10/30/90)

Consider the following code fragment:
-----------
float *ff (p) float p;
{
 static float gv;
 gv = p; return &gv;
}
main ...
{ printf ("= %f\n", *(ff((float)1.0)) + *(ff((float)2.0))); ... }
-----------
Everyone *expects* the answer to be 3.0 (approx; change 'float' to
'int' if you do not like rounding errors in the example...). However,
can a conforming implementation return (a) 1+1=2, or (b) 2+2=4 ??
(Yes, a well-known compiler returns (a) even without code opt.)
Thanx in advance,
----------------------------------------------------------------------------
Andre' Dolenc                              Helsinki University of Technology
Research Associate                         TKO, Otakaari 1A, Espoo
Email (Internet): ado@sauna.hut.fi         SF-02150  Finland
----------------------------------------------------------------------------

steve@taumet.com (Stephen Clamage) (10/31/90)

ado@sauna.hut.fi (Andre Dolenc) writes:

|Consider the following code fragment:
|-----------
|float *ff (p) float p;
|{
| static float gv;
| gv = p; return &gv;
|}
|main ...
|{ printf ("= %f\n", *(ff((float)1.0)) + *(ff((float)2.0))); ... }
|-----------
|Everyone *expects* the answer to be 3.0 (approx; change 'float' to
|'int' if you do not like rounding errors in the example...). However,
|can a conforming implementation return (a) 1+1=2, or (b) 2+2=4 ??

Well, I must not be everyone.  I certainly don't expect the answer to
be 3.0.  A conforming implementation must evaluate both calls to ff()
before calling printf() -- that is all that is assured.  The ANSI
standard explicity says that the order in which side effects occur
between sequence points is unspecified.
-- 

Steve Clamage, TauMetric Corp, steve@taumet.com