Trap Representation
Question:
Answer:
1. Trap Representation:
In C, a trap representation is a bit pattern that fits the size of a type but causes undefined behavior if used as a value of that type. No type is required to have trap representations, but the only type guaranteed not to have them is unsigned char.
An example of a trap representation is a signaling NaN in a floating-point type. These patterns are undefined in C99.
2. Applicability to C :
Although the question does not mention C , it's worth noting that the concept of trap representations applies to C as well.
3. Binary Representation of Float and Pointer:
The code provided below exhibits undefined behavior:
float f = 3.5; int *pi = (int*)&f;
However, this behavior is not related to trap representations. To obtain the integer value with the same bit pattern as the float, use the following code:
int extract_int(float f) { union { int i; float f; } u; u.f = f; return u.i; }
This code exhibits unspecified behavior in C99, meaning the standard does not define the exact integer value produced, but it guarantees that a valid integer value is obtained. Therefore, the binary representation of the float and the integer obtained using the union are not guaranteed to be identical.
The above is the detailed content of What are Trap Representations in C and C , and Do Identical-Sized Floats and Their Pointers Share the Same Binary Representation?. For more information, please follow other related articles on the PHP Chinese website!