delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/12/02/22:53:27

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: how to interpret this...
Date: Mon, 02 Dec 1996 18:48:57 -0800
Organization: Three pounds of chaos and a pinch of salt
Lines: 69
Message-ID: <32A39519.42FF@cs.com>
References: <57ve1o$rfk AT lyra DOT csx DOT cam DOT ac DOT uk>
Reply-To: fighteer AT cs DOT com
NNTP-Posting-Host: ppp109.cs.com
Mime-Version: 1.0
To: "G.P. Tootell" <gpt20 AT thor DOT cam DOT ac DOT uk>
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

G.P. Tootell wrote:
> 
> i'm used to doing a=b=c=0; to set more than one variable at a time, and by error
> i had extended this analogy to if (a==b==c==0) { do stuff }
> no djgpp didn't throw up any errors about this even with -wall and indeed ran the
> compiled code fine. however the interpretation of this is not what i expected.
> instead of treating this as a==b && b==c && c==0, it treated it as a==b && c==0
> can anyone explain this behavior? should it not have been reported as a warning?

Although the compiler does a very good job at spotting unsafe operator
combinations, it cannot possibly interpret the intentions of every piece
of code you write.  The reason it barfs about things like ( a = b == c )
is because it's extremely unlikely that that is what the programmer
actually intended, and the compiler has been told to remind him/her of
this.

Your expression above is perfectly okay syntactically, and is evaluated
according to the internal order of operations of the compiler.  Since,
according to ANSI C, this may differ from compiler to compiler, I'll
present the simplest example:

0.    ( a == b == c == 0 )

Since all the operations are at the same order of precedence, they are
evaluated left-to-right.

1.    ( ( ( a == b ) == c ) == 0 )

Now, plug in numbers which satisfy the original intention.

Given:  a = 0
	b = 0
	c = 0

2.    ( ( ( 0 == 0 ) == 0 ) == 0 )

3.    ( ( 1 == 0 ) == 0 )

4.    ( 0 == 0 )

5.    1

Interestingly, this evaluates to true, but consider a different set of
numbers.

Given:	a = 1
	b = 1
	c = 0

2.    ( ( ( 1 == 1 ) == 0 ) == 0 )

3.    ( ( 1 == 0 ) == 0 )

4.    ( 0 == 0 )

5.    1

This, also comes out true, which is syntactically correct but wrong
according to the original intention of the algorithm.

-- 
John M. Aldrich, aka Fighteer I <fighteer AT cs DOT com>

-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCS d- s+:- a-->? c++>$ U@>++$ p>+ L>++ E>+ W++ N++ o+ K? w(---) O-
M-- V? PS+ PE Y+ PGP- t+(-) 5- X- R+ tv+() b+++ DI++ D++ G e(*)>++++
h!() !r !y+()
------END GEEK CODE BLOCK------

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019