IsUnsigned() function?

Rick Jones rick at tetrauk.UUCP
Wed Jul 25 03:26:29 AEST 1990


I'm suprised that very few people seems to have grasped what the question was
about.  I don't have a copy of the original posting, but as I remember the
question was "how do you write a function or macro to determine if a variable is
unsigned" (or something like that).

The question was not "is the value negative", that is absurdly trivial, it was
to test for the declaration style - maybe to find if an unqualified char is
signed or unsigned, since it can be either.

The red herring in the question is the word "function".  You can't do it with a
function, since the type of a function's formal parameter is defined within the
function, it cannot be passed via the call.  So the first answer is that it has
to be a macro, which will operate on its argument according to the declaration
of that argument.

The essential characteristic of an unsigned value is that it can never be
negative, and the essential characteristic of a signed value is that
complementing its most significant bit will change its sign (assuming 2's
complement representation, which is pretty safe).  Since the other bits are
irrelevant to this test, you can complement them all and get the same result.

Therefore try the following:

#define IsUnsigned(a)	(a >= 0 && ~a >= 0)


It does work - I've tested it.

-- 
Rick Jones					You gotta stand for something
Tetra Ltd.  Maidenhead, Berks			Or you'll fall for anything
rick at tetrauk.uucp (...!ukc!tetrauk.uucp!rick)	     - John Cougar Mellencamp



More information about the Comp.lang.c mailing list