🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.sys.mac
Article #23148

Re: Lightspeed C bug?

#23148
From: David W. Berry
Date: Thu, 24 Dec 1987 20:50
52 lines
2285 bytes
In article <870081@hpcilzb.HP.COM> cnc@hpcilzb.HP.COM (Chris Christensen) writes:
>I have been having a real head-scratcher problem with Lightspeed C.
>
>I am trying to generate random numbers from 0 to 7.
>
>I use
>
>#define ABS(x) (((x) < 0) ? -(x) : (x))
>x = ABS(Random()) % 8;
>
>I get random numbers from -7 to 7
>
	Remember that C macros are simple text substitution.  Thus what
the compiler will see (after the preprocessor gets through with it) is:
	x = (((Random()) < 0) ? -(Random()) : (Random())) % 8;
so you're actually calling Random twice for each statement, once to
randomly decide whether or not to negate the value of the second
Random.  This probably isn't what you want :-).

>I use
>
>x = Random();
>x = ABS(x);
>x %= 8;
>
>I get the desired range.
	One would expect it to.  You only call Random one time and then
take the absolute value.  It would also work to use 'x = ABS(x) % 8'
>
>This is the define for Absolut that I have always used. Why doesn't this work?
>Am I being bitten by a "one pass" compiler bug?
	Actually, you're being bitten by a language design feature.
If you're C compiler doesn't do it this way it's a bug.  Remember,
don't call subroutines or do things with side effects inside of
macro usage.  Other things to watch out for are things like:
	while(isalpha(*p++))
which will sometimes do what's expected and sometimes not, and certainly
isn't portable.
>
>--------------------------------------------------------------------------------
>Chris Christensen				Hewlett-Packard
>(408) 553-2955 or telnet 553-2955		Design Technology Center
>cnc%hpdtc@hplabs.hp.com			Santa Clara, CA
>...!hplabs!hpcid!cnc


-- 
	David W. Berry
	dwb@well.uucp                   dwb@Delphi
	dwb@apple.com                   973-5168@408.MaBell
Disclaimer: Apple doesn't even know I have an opinion and certainly
	wouldn't want if they did.
Technical Details
Message-ID: <7110@apple.UUCP>
Path: arc1-ca.pugleaf.net!utzoo!mnetor!uunet!lll-winken!lll-lcc!pyramid!voder!apple!dwb
References: <870081@hpcilzb.HP.COM>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!mnetor!uunet!lll-winken!lll-lcc!pyramid!voder!apple!dwb
From: dwb@apple.UUCP (David W. Berry)
Newsgroups: comp.sys.mac
Subject: Re: Lightspeed C bug?
Message-ID: <7110@apple.UUCP>
Date: 24 Dec 87 20:50:08 GMT
References: <870081@hpcilzb.HP.COM>
Reply-To: dwb@apple.UUCP (David W. Berry)
Organization: Apple Computer Inc., Cupertino, USA
Lines: 51