Index Home About Blog
Newsgroups: fa.linux.kernel
From: Linus Torvalds <torvalds@osdl.org>
Subject: Re: (0 == foo), rather than (foo == 0)
Original-Message-ID: <Pine.LNX.4.58.0403101832580.1045@ppc970.osdl.org>
Date: Thu, 11 Mar 2004 02:31:24 GMT
Message-ID: <fa.gue5uu3.92grph@ifi.uio.no>

On Thu, 11 Mar 2004, Peter Williams wrote:
> Richard B. Johnson wrote:
> >
> > People who develop kernel code know the difference between
> > '==' and '=' and are never confused my them.
>
> And you never make typing mistakes?  That's admirable or should I say
> incredible.

The thing is, people tend to make fewer typing mistakes of that kind, than
just plain logic errors from not thinking right about something.

And while "0 == foo" may be logically the same thing as "foo == 0", the
fact is, the latter is what people are used to seeing. And by being used
to seeing it, they have an easier time thinking about it.

As a result, using the former just tends to increase peoples confusion by
making code harder to read, which in turn tends to increase the chance of
bugs.

So don't do it. The kind of bug that the "0 == x" syntax protects against
is LESS LIKELY to happen than the kind of bug it tends to cause.

		Linus


Newsgroups: fa.linux.kernel
From: Linus Torvalds <torvalds@osdl.org>
Subject: Re: (0 == foo), rather than (foo == 0)
Original-Message-ID: <Pine.LNX.4.58.0403101917060.1045@ppc970.osdl.org>
Date: Thu, 11 Mar 2004 03:14:29 GMT
Message-ID: <fa.gru3ue8.bier9k@ifi.uio.no>

On Thu, 11 Mar 2004, Peter Williams wrote:
>
> As somebody pointed out -Wall will (help) detect most of these errors by
> suggesting () be placed around any expression of the form a = b that
> occurs inside a simple boolean expression which will cause those people
> who care about eliminating warning messages to reevaluate the code and
> make sure they really meant a = b and replace it with (a = b) to get rid
> of the warning error.

Actually, don't just add parenthesis. They get rid of the warning, but
they don't actually make for very pretty reading.

I don't know why the gcc warning suggests adding parentheses, since they
have no semantic meaning, and are _horrible_ from a syntactic standpoint.

The warning should be there whether there are parenthesis or not, and it
should state that you should have an explicit inequality expression. So if
you have

	if (a = b)
		...

and you really _mean_ that, then the way to write it sanely is to just
write it as

	if ((a = b) != 0)
		...

which makes it much clearer what you're actually doing.

		Linus

Index Home About Blog