>In article <11**********************@m7g2000cwm.googlegroups. com>,
<na****@gmail.comwrote:
[with vertical compression by me]
>>int g_index = 0; // global
int bar() { g_index++; return 17; }
int foo() {
int array[10];
array[g_index] = bar();
}
>>Is *this* thing defined in the C specification? (*this* as opposed to
the order of function evaluation, which I understand is not defined).
The precise answer is that it is "unspecified".
In article <eh**********@canopus.cc.umanitoba.ca>
Walter Roberson <ro******@ibd.nrc-cnrc.gc.cawrote:
>There are subtle nuances to sequence points that I don't think I
am clear on myself. Puzzling through the C89 wording, I -think- the
above is not valid.
Depends what you mean by "valid".
The sequence points that surround the call to, and return from,
function bar(), guarantee that g_index is 0 before, and 1 after,
the call to bar(). (Assuming of course that it has not been altered
before this.) In addition, we can (I believe) be sure that in the
left-hand sub-expression "array[g_index]", g_index is evaluated
either entirely before, or entirely after, the call to bar(). It
will therefore be either 0 or 1.
Unfortunately, there is nothing that says *which* will occur. This
is not even "implementation-defined". If it were, the programmer
could read the documentation that comes with the compiler, and find
out whether array[g_index] will be array[0] or array[1], and know
the answer for that particular compiler (perhaps "that compiler with
specific flags", since there might be a compiler switch to choose
one or the other). But it is "unspecified", meaning the compiler
does not even have to tell you how it chooses when to evaluate
g_index (i.e., before or after the call to bar()).
That, in turn, means the compiler can make this choice based on
the phase of the moon, the temperature of the CPU, or any other
hard-to-predict item. You can be sure of "zero or one", but not
which.
The way to force the desired order of evaluation -- whatever that
is -- is to capture g_index with a sequence point that is ordered
with respect to the function-call sequence point. For instance:
i = g_index; /* capture value before the call */
array[i] = bar(); /* index with old value */
or:
i = bar(); /* do the call */
array[g_index] = i; /* index with new value */
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.