HP C Programmer's Guide (92434-90009)

132 Chapter5
Programming for Portability
General Portability Considerations
such an expression against zero may not produce the object code you expect as the
following example illustrates.
main()
{
int i;
i=2;
if ((i-sizeof(i)) < 0) /* sizeof(i) is 4,
but unsigned! */
printf("test less than 0\n");
else
printf("an unsigned expression cannot be less than 0\n");
}
When run, this program will print
an unsigned expression cannot be less than 0
because the expression (i-sizeof(i)) is unsigned since one of its operands is unsigned
(sizeof(i)). By definition, an unsigned number cannot be less than 0 so the compiler will
generate an unconditional branch to the else clause rather than a test and branch.
Bit-Fields
The ANSI C definition does not prescribe bit-field implementation; therefore each vendor
can implement bit-fields somewhat differently. This section describes how bit-fields are
implemented in HP C.
Bit-fields are assigned from most-significant to least-significant bit on all HP-UX and
Domain systems.
On all HP-UX implementations, bit-fields can be signed or unsigned, depending on how
they are declared.
On the Series 300/400, a bit-field declared without the signed or unsigned keywords will
be signed in ANSI mode and unsigned in compatibility mode by default.
On the Series 700/800, plain int, char,orshort bit-fields declared without the signed or
unsigned keywords will be signed in both compatibility mode and ANSI mode by default.
On the Series 700/800, and for the most part on the Series 300/400, bit-fields are aligned so
that they cannot cross a boundary of the declared type. Consequently, some padding within
the structure may be required. As an example,
struct foo
{
unsigned int a:3, b:3, c:3, d:3;
unsigned int remainder:20;
};
For the above struct, sizeof(struct foo) would return 4 (bytes) because none of the
bit-fields straddle a 4 byte boundary. On the other hand, the following struct declaration
will have a larger size:
struct foo2
{
unsigned char a:3, b:3, c:3, d:3;