Sheldon Juncker - 1 year ago 65

C Question

In C, is there a guarantee that two doubles whose values are equal (

`double1 == double2`

Answer Source

There is no such guarantee.

For example, in IEEE floating point format, there exists the concept of negative 0. It compares equal to positive 0 but has a different representation.

Here's an example of that:

```
#include <stdio.h>
int main()
{
unsigned long long *px, *py;
double x = 0.0, y = -0.0;
px = (unsigned long long *)&x;
py = (unsigned long long *)&y;
printf("sizeof(double)=%zu\n",sizeof(double));
printf("sizeof(unsigned long long)=%zu\n",sizeof(unsigned long long));
printf("x=%f,y=%f,equal=%d\n",x,y,(x==y));
printf("x=%016llx,y=%016llx\n",*px,*py);
return 0;
}
```

Output:

```
sizeof(double)=8
sizeof(unsigned long long)=8
x=0.000000,y=-0.000000,equal=1
x=0000000000000000,y=8000000000000000
```