IsUnsigned() function?

Karl Heuer karl at haddock.ima.isc.com
Fri Jul 27 16:06:43 AEST 1990


In article <619 at .tetrauk.UUCP> rick at tetrauk.UUCP (Rick Jones) writes:
>In <17147 at haddock.ima.isc.com> karl at 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 at kelp.ima.isc.com or ima!kelp!karl), The Walking Lint



More information about the Comp.lang.c mailing list