How is this implementation of fabs() working?

c, floating-point

Solution

The code is technically invalid C as it breaks strict aliasing rules. However, if you tell your compiler not to abuse the aliasing rules and you're guaranteed that `double`s and `int`s are laid out in memory as they are on an x86:

`(int *)&x` is a pointer to `x`. Adding 1 moves the pointer forward by 4 bytes. Dereferencing it gives you the 4th through 7th bytes of the `double`. You mask off the high bit of this because that is the last byte of the `double`.

Incidentally, you can stop this from being an aliasing violation by using a `char *` and adding 7 instead of 1. It's still horribly nonportable.

Problem

The algorithm for finding the absolute value of a floating point number over here. How does this work? ``` //find absolute value double x; *(((int *) &x) + 1) &= 0x7fffffff; ``` I don't understand why the offset of 1 was necessary. It says: the IA32 64-bit sign bit is 0x80000000 at an int address offset of +1. Can someone break this down and explain?

Original source