In article <vt*******************@rwcrnsc51.ops.asp.att.net >,
av <va*****@iit.edu> wrote:
First of all, my newsreader says you set follow-up to "Re: order of
execution". Please try to avoid such nonsense in the future.
Joona I Palaste wrote:
copx <in*****@invalid.com> scribbled the following: I wonder if something like this
would be save/portable:
m = find_slot();
if (m != NOT_FOUND && list[m].state == OK) {
..
The question is: Is it guaranteed
that the "list[m].state == OK" check
is NOT executed if the "m != NOT_FOUND"
is FALSE?
Yes it is guaranteed.
Is this something that is a defined behaviour of the ANSI C compiler
standard?
I can think of compilers, which might decide to optimize the above code,into
slightly different assmembly code, when heavy optimization is turned on.
There are two rules for a compiler: First, it has to do everything
exactly as the C Standard says. In this example, the right hand side of
an && must _not_ be evaluated if the left hand side is false. Second,
the compiler can cheat as much as it likes if you can't tell the
difference.
An example:
if (x > 0 && x < 10) ...
Strictly speaking, the compiler must test (x > 0) first. If that is
false, then it must not test (x < 10). However, you could never see the
difference. So the compiler is allowed in this case to test (x < 10)
first or test both conditions simultaneously. You will still get exactly
the same result as if the compiler had gone by the rules.
A second example:
int * p; ...;
if (p != NULL && *p == 10)...
Strictly speaking, the compiler must not test (*p == 10) if p is a null
pointer. Lets say use a computer that would crash when testing *p == 10
if p is NULL. So obviously you _can_ tell the difference if the compiler
cheats, therefore the compiler is not allowed to cheat.
There are computers where testing (*p == 10) would just produce a result
of true or false, even if p is a null pointer. On such a computer, the
compiler would be allowed to cheat, because you couldn't tell the
difference. And it is ok, exactly because you cannot tell the
difference.
Now there might be a computer where it is guaranteed by the hardware
that reading *p will give a value of 0 if p is a null pointer. On such a
computer, the compiler would be allowed to change the whole test to "if
(*p == 10)". Again, you couldn't tell the difference.
So altogether, the compiler can do whatever it likes, as long as it
guarantees that you get exactly the results that you should get
according to the C Standard. In other words, you will get the right
result.