Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!ncar!ico!haddock!karl From: karl@haddock.ima.isc.com (Karl Heuer) Newsgroups: comp.lang.c Subject: Re: IsUnsigned() function? Message-ID: <17158@haddock.ima.isc.com> Date: 27 Jul 90 06:06:43 GMT References: <1990Jul16.214155.5087@Neon.Stanford.EDU> <2936@mtung.ATT.COM> <1990Jul22.154326.19680@ux1.cso.uiuc.edu> <615@tetrauk> <17147@haddock.ima.isc.com> <619@.tetrauk.UUCP> Reply-To: karl@kelp.ima.isc.com (Karl Heuer) Organization: Interactive Systems, Cambridge, MA 02138-5302 Lines: 37 In article <619@.tetrauk.UUCP> rick@tetrauk.UUCP (Rick Jones) writes: >In <17147@haddock.ima.isc.com> karl@kelp.ima.isc.com (Karl Heuer) writes: >>>#define IsUnsigned(a) (a >= 0 && ~a >= 0) >> >>Trivia question: under what circumstances will Rick's macro produce the wrong >>answer to the presumed question? > >Perhaps I should try to answer that myself! >a. If signed arithmetic does not use 2's complement notation Actually I had a more specific answer in mind--even on such machines it works for *most* values. I think there are only two exceptions: a1. The signed value 0 on a one's complement machine a2. The signed value INT_MAX on a sign-magnitude machine In both cases ~a is -0, which is >= 0 despite having the sign bit set. >b. For types shorter than int if the compiler's promotion is wrong > >The promoted type retains the signedness of the shorter type (that's my >understanding, anyway) Nope. Classic C compilers are divided on the issue, and ANSI C requires value-preserving rather than unsigned-preserving promotion. So, if short is 16 bits and int is 32, unsigned short promotes to signed int. Also: c. If the argument is an expression whose primary operator with sufficiently low precedence, e.g. `IsUnsigned(1||1)'. (Fix: parenthesize the two instances of `a' in the macro body.) d. If the arg is an expression with side effects, e.g. `IsUnsigned(*p++)' where `int *p' points into `{ 1, ~1 }'. (Fix: use an algorithm that evaluates the arg only once. Not a problem in practice, since the only use for this macro is in a situation where the side effects would wreak havoc anyway.) Karl W. Z. Heuer (karl@kelp.ima.isc.com or ima!kelp!karl), The Walking Lint