Message from discussion Question about platform independent code and ANSI C compliant code
From: Dann Corbit <dcor...@connx.com>
Subject: Re: Question about platform independent code and ANSI C compliant code
Date: Thu, 3 Jun 2010 06:26:50 -0700
Organization: A noiseless patient Spider
References: <email@example.com> <MPG.firstname.lastname@example.org> <email@example.com> <firstname.lastname@example.org> <2BKNn.1558$kL6.847@hurricane> <0.fafda0c28fab87afab6f.20100603125850BST.email@example.com> <SDNNn.1596$jL2.533@hurricane>
Content-Type: text/plain; charset="us-ascii"
Injection-Date: Thu, 3 Jun 2010 13:26:50 +0000 (UTC)
Injection-Info: mx02.eternal-september.org; posting-host="s1nvOyg/Sn+a63BHm0iozg";
logging-data="27083"; mail-complaints-to="ab...@eternal-september.org"; posting-account="U2FsdGVkX1+Y/M9lqFyah1I0r9cr/REntmm7dzp2Jek="
In article <SDNNn.1596$jL2.533@hurricane>, ba...@freeuk.com says...
> "Ben Bacarisse" <ben.use...@bsb.me.uk> wrote in message
> > "bart.c" <ba...@freeuk.com> writes:
> >> unsigned short a;
> >> int b=123456;
> >> a=b;
> >> 'a' may end up as 57920 on some machines, and likely 123456 on
> >> others. It seems reasonable to be able to request 'a' to be exactly
> >> 16-bits on any machine, whether that is natural for the architecture
> >> on not.
> > In a rather limited way, you can: you can use a 16-bit wide bit-field.
> > I suppose a conforming C compiler may be permitted to refuse to allocate
> > such a bit-field but that seems to stretch the letter of the law beyond
> > what is reasonable.
> > There are a lot of things you can't do with bit-fields, but they do
> > provide automatically masked and promoted integer arithmetic. On
> > balance, though, I'd write the code to use "at least 16 bits" and put
> > the masks in myself.
> But then, on a machine where C shorts are actually 16-bits, you have to rely
> on the compiler to remove the unnecessary masks.
> Also, where the intention is to have arrays of such values, then bit-fields
> may not work, while simple masking is insufficient, needing shifts and masks
> instead, which would be silly where the machines does directly support
Portability may have a cost, in other words. There is no other way that
is fully portable, since the exact width types of C99 are optional.
The O.P.'s goal seems to be some kind of extreme portability. If you
need exact widths, and you need it to work everywhere, then you need bit
I also doubt that bit fields manipulations will be the bottleneck of any
important operations with the bit fields.
So I think it comes down to these choices:
1. Total portability with bit fields. (Some cost in efficiency and
convenience: arrays, addresses, etc.)
2. Total speed via separate functions for each hardware system (huge
cost in debugging and maintenance)
3. Careful analysis to ensure that the native integral sizes perform
the operations in a satisfactory manner. (huge design effort needed)
I don't know which option is best.