Home >Backend Development >C++ >What are Trap Representations in C and How Do They Differ from Undefined Behavior?

What are Trap Representations in C and How Do They Differ from Undefined Behavior?

Barbara Streisand
Barbara StreisandOriginal
2024-12-20 00:02:14557browse

What are Trap Representations in C and How Do They Differ from Undefined Behavior?

Trap Representation in C: An Elaboration

What is a Trap Representation?

C99 introduces the term "trap representation" to describe bit patterns that occupy a type's size yet trigger undefined behavior if used as values of that type. The existence of these patterns is optional, except for unsigned char, which is guaranteed to avoid them.

One example of a trap representation is a signaling NaN in floating-point types. Its behavior is undefined in C99, even though IEC 60559 specifies its handling.

Null Pointers and Trap Representations

While pointer types can possess trap representations, null pointers are not considered such. Undefined behavior only arises when they are dereferenced or offset. Trap representations, on the other hand, cause undefined behavior upon simple read operations with their representative type.

Undefined Behavior vs. Trap Representation

The code you provided exhibits undefined behavior due to pointer-aliasing rules, not trap representations. To correctly convert a float to an int with the same representation, use the following code snippet:

int extract_int(float f)
{
    union { int i; float f; } u;
    u.f = f;
    return u.i;
}

This code exhibits unspecified behavior in C99, where the exact integer value produced is not defined, but a valid integer result is guaranteed. It is not a trap representation and cannot be optimized away based on assumptions about its absence.

The above is the detailed content of What are Trap Representations in C and How Do They Differ from Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn