...
Non-Compliant Code Example (Ints vs. Floats)
The following non-compliant code demonstrates the perils of operating on data of improper types. It tries to increment an int typecast as a float, and a float typecast as an int, and displays the results.
...
Compliant Solution (Ints vs. Floats)
Here In this compliant solution, the pointers are assigned to the variables of the proper data types.
...
Bit-fields can be used to allow flags or other integer values with small ranges to be packed together to save storage space. Bit-fields can improve the storage efficiency of structures. Compilers typically allocate consecutive bit-field structure members into the same int
-sized storage, as long as they fit completely into that storage unit. However, the order of allocation within a storage unit is implementation-defined. Some implementations are "right-to-left": the first member occupies the low-order position of the storage unit. Others are "left-to-right": the first member occupies the high-order position of the storage unit. Calculations that depend on the order of bits within a storage unit may produce different results on different implementations.
...
Non-Compliant Code Example (Bit-Field Overlap)
In this the following non-compliant examplecode, assuming eight bits to a byte, if bit-fields of six and four bits are declared, is each bit-field contained within a byte or are the bit-fields split across multiple bytes?
Code Block | ||
---|---|---|
| ||
struct bf { unsigned int m1 : 6; unsigned int m2 : 4; }; void function() { unsigned char *ptr; struct bf data; data.m1 = 0; data.m2 = 0; ptr = (unsigned char *)&data; ptr++; *ptr += 1; /* what does this increment? */ } |
In the above example, if If each bit-field lives within its own byte, then m2
(or m1
, depending on alignment) is incremented by 1. If the bit-fields are indeed packed across 8-bit bytes, then m2
might be incremented by 4.
...