correct • elegant • free

△ Comp.lang.c △

◅ Structure problem

Multiple EOF's when scanning a file. ▻

Problems with the & and && operators

In article <>,
Ben Pfaff  <> wrote:
>Ludovic PITHON <> writes:
>>     if ( a != NULL && *a == 5) ; /* is correct. */
>>     if ( a != NULL & *a==5) ; /* have a "segmentation fault" result if a ==
>> NULL. */
>I see no difference in behavior between the two statements.  Care
>to clarify?

The logical operators `&&' and `||' guarantee "short circuit" (or
"lazy") evaluation in C.  That is, it is guaranteed that the left
hand expression will be evaluated first; the right hand will only be
evaluated if it is needed.

What does "needed" mean here?  A `&&' expression is true if and only if
both its left hand side and its right hand side are true.  So if the
left hand side is false, we immediately know that the overall expression
is false.

Similarly, a `||' expression is false if and only if both sides are
false.  In this case, we can stop if the left hand side evaluates to
true: the overall expression must be true, whatever the value of the
right hand side.

So, in these expressions, the right hand side will never be evaluated.

    0 && x
    1 || x

(In these trivial examples, the left hand side is a constant, and a good
compiler will eliminate the right hand side entirely.  But even a shoddy
compiler will never evaluate it.)

Ludovic's first example, then, will only dereference `a' if it is not
null.  It is equivalent to this.

    if (a != NULL)
            if (*a == 5) ...

C programmers take advantage of this guaranteed short circuit behaviour
all the time.  (One of Kernighan's objections in "Why Pascal is not my
favourite programming language" was the lack of short-circuit Boolean
operators in Pascal, although I seem to recall that Turbo Pascal had
them as an extension.)

The arithmetic operators `&' and `|' do not (can not) have this short
circuit behaviour.  Therefore, Ludovic's second example will always
dereference `a', even if it is NULL.

Tim Goodwin   | "If you don't know what closures are, you probably don't
Leicester, UK | want to know what closures are." -- Larry Wall

Original headers:

From: (Tim Goodwin)
Newsgroups: comp.lang.c
Subject: Re: Problems with the & and && operators
Date: 4 Feb 2000 16:49:30 -0000
Message-ID: <87evvg$av7$>
References: <>

△ Comp.lang.c △

◅ Structure problem

Multiple EOF's when scanning a file. ▻