...
This example is noncompliant, for example, on an implementation where pointers are 64 bits and unsigned integers are 32 bits because the result of converting the 64-bit ptr cannot be represented in the 32-bit integer type.
...
Noncompliant Code Example
In this noncompliant code example, the pointer ptr
is converted to an integer value. Both a pointer and an int
are assumed to be 32 bits. The high-order 9 bits of the number are used to hold a flag value, and the result is converted back into a pointer. This example is noncompliant, for example, on an implementation where pointers are 64 bits and unsigned integers are 32 bits because the result of converting the 64-bit ptr cannot be represented in the 32-bit integer type.
Code Block | ||||
---|---|---|---|---|
| ||||
char *ptr; unsigned int flag; /* ... */ unsigned int number = (unsigned int)ptr; number = (number & 0x7fffff) | (flag << 23); ptr = (char *)number; |
...
Please note that this noncompliant code example also violates EXP11-C. Do not make assumptions regarding the layout of structures with bit-fields.
Compliant Solution
Saving a few bits of storage is generally not as important as writing portable code. A struct
can be used to provide room This compliant solution uses a struct
to provide storage for both the pointer and the flag value. This solution is portable to machines of different word sizes, both smaller and larger than 32 bits, working even when pointers cannot be represented in any integer type.
Code Block | ||||
---|---|---|---|---|
| ||||
struct ptrflag { char *pointer; unsigned int flag :9; } ptrflag; char *ptr; unsigned int flag; /* ... */ ptrflag.pointer = ptr; ptrflag.flag = flag; |
...