Aliasing and effective type

suggest change

Two expressions alias when they can access the same stored object. Aliasing matters because a write through one expression can change the value observed through another.

The effective-type rules restrict which lvalue types may be used to access an object's stored value. Permitted cases include:

The complete rules are more precise than the common slogan “different pointer types cannot alias.” A cast changes a pointer's type but does not grant permission to access an object through an incompatible lvalue.

float value = 1.0f;
int *bits = (int *)&value;
int representation = *bits; /* Undefined behavior: incompatible access. */

Use memcpy to copy an object representation into another object without violating aliasing rules:

#include <assert.h>
#include <stdint.h>
#include <string.h>

int main(void)
{
    float value = 1.0f;
    uint32_t representation;

    static_assert(sizeof representation == sizeof value, "size mismatch");
    memcpy(&representation, &value, sizeof representation);
}

The copied integer value depends on the floating-point representation and byte order, but the copy itself does not violate effective type or alignment requirements.

Dynamically allocated storage has special effective-type rules because it initially has no declared type. Storing through a non-character lvalue or copying from another object establishes an effective type for later accesses. Prefer allocating storage for a known destination type and accessing it consistently through that type.

Compilers use aliasing information for optimization. Code that violates these rules may appear to work in one build and fail after optimization, so warning-free casts are not evidence that type-punning is valid.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents