How to resolve a warning: dereferenced type-guard pointer violates strict anti-aliasing rules

    #define HTON_I32(x) htonl(x)
inline float  __HTON_F32(float  x)
{
    int i = HTON_I32(*((int *)(&x)));
    return (*((float *)(&i)));
}

How to resolve the warning dereferencing type-punned pointer will break strict-aliasing rules in the above code

+5
source share
2 answers

Eliminate type-punning and replace it with one that is not fragile in the face of smoothing:

#include <string.h>

inline float __HTON_F32(float x) {
    int i;
    memcpy(&i, &x, sizeof x);
    i = HTON_I32(i);
    memcpy(&x, &i, sizeof x);
    return x;
}

Intelligent optimizing compilers will skip calls memcpyand generate equivalent (sometimes better) code for what you get from punning.

Another common solution you will see is unions. All of these solutions suggest that sizeof(int) == sizeof(float). You can add a statement about this.

+9
source

-punning, (C99: TC3 , ):

#include <stdint.h>

inline float __HTON_F32(float x) {
    union { float as_float; int32_t as_int; } value = { x };
    value.as_int = HTON_I32(value.as_int);
    return value.as_float;
}
+1

All Articles