[comp.lang.c] Determining machine characteristics

karl@haddock.ima.isc.com (Karl Heuer) (07/25/90)

In article <1990Jul22.154326.19680@ux1.cso.uiuc.edu> mcdonald@aries.scs.uiuc.edu (Doug McDonald) writes:
>[Assuming the question was to analyze the *type*, can it be done portably?]

Already solved, see my earlier post.

>To extend it a bit, how about macros for [the format of negative numbers]

Assuming there are only the three possibilities,
	#define is_twos_complement() ((-2 | -3) == -1)
	#define is_ones_complement() ((-1 & -2) == -3)
	#define is_sign_magnitude()  ((-1 | -2) == -3)
should distinguish them.

>word_size(a), which returns the number of bits in a

I suppose the simple solution
	#include <limits.h>
	#define word_size(a) (sizeof(a)*CHAR_BIT)
is cheating.  Hmm, if you want it to be *completely* portable, allowing for
arbitrarily large values of CHAR_BIT (64 might actually be a reasonable option
on a Cray!), I can't think of a way to do it offhand.

I'd also like to be able to do `is_big_endian()' and `is_little_endian()', but
I think these require run-time code.

Karl W. Z. Heuer (karl@kelp.ima.isc.com or ima!kelp!karl), The Walking Lint

ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) (07/26/90)

In article <17148@haddock.ima.isc.com>, karl@haddock.ima.isc.com (Karl Heuer)
provides some nice macros
> 	#define is_twos_complement() ((-2 | -3) == -1)
> 	#define is_ones_complement() ((-1 & -2) == -3)
> 	#define is_sign_magnitude()  ((-1 | -2) == -3)
and says
> I'd also like to be able to do `is_big_endian()' and `is_little_endian()', but
> I think these require run-time code.

It's clear that an arithmetic expression which appears in _code_ must be
evaluated as if evaluated by the target machine, but need arithmetic
expressions in #ifs be evaluated the same way?  Is it possible for
	#if is_ones_complement()
to succeed and
	if (is_ones_complement())
to fail?

-- 
Science is all about asking the right questions.  | ok@goanna.cs.rmit.oz.au
I'm afraid you just asked one of the wrong ones.  | (quote from Playfair)

will@kfw.COM (Will Crowder) (07/27/90)

In article <3473@goanna.cs.rmit.oz.au> ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) writes:

>It's clear that an arithmetic expression which appears in _code_ must be
>evaluated as if evaluated by the target machine, but need arithmetic
>expressions in #ifs be evaluated the same way?  Is it possible for
>	#if is_ones_complement()
>to succeed and
>	if (is_ones_complement())
>to fail?

Yes, it is quite possible for that to fail.  The C preprocessor knows 
nothing about the C language itself.  For instance, try using a cast
in a preprocessor #if.

Will