Violating the strict aliasing rules

suggest change

In the following code let us assume for simplicity that float and uint32_t have the same size.

#include <stdint.h>
#include <stdio.h>

void fun(uint32_t *u, float *f) {
    float a = *f;
    *u = 22;
    float b = *f;
    printf("%g should equal %g\n", a, b);
}

u and f have different base type, and thus the compiler can assume that they point to different objects. There is no possibility that *f could have changed between the two initializations of a and b, and so the compiler may optimize the code to something equivalent to

void fun(uint32_t *u, float *f) {
    float a = *f;
    *u = 22;
    printf("%g should equal %g\n", a, a);
}

That is, the second load operation of *f can be optimized out completely.

A call with two different objects is defined. *u = 22 does not change *f, so the program prints something like

4 should equal 4

Passing the same object through both pointer types violates strict aliasing, and the behavior is undefined. The compiler may keep the optimized form and print 4 twice, or it may reload *f and print a different bit pattern. Either result, or any other result, is allowed.

int main(void)
{
    float fval = 4;
    uint32_t uval = 77;
    fun(&uval, &fval); /* defined */

    fun((uint32_t *)&fval, &fval); /* undefined behavior */
}

Feedback about page:

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



Table Of Contents