Why two NaNs with the same binary are still not equal to each other but two infs are?
15:49 17 Feb 2026

Nans and infs are not numbers, mathematical operations are not defined for them. Yet, when we compare two infs using the built in method or bitwise methos C lets them to be equal to each other provided that they are the same in binary.

#include 
int main()
{
    unsigned char bin1[] = {0b00000000, 0b00000000, 0b00000000, 0b0000000, 0b00000000, 0b0000000, 0b11110000, 0b01111111};
    unsigned char bin2[] = {0b00000000, 0b00000000, 0b00000000, 0b0000000, 0b00000000, 0b0000000, 0b11110000, 0b01111111};
    double num1 = *(double *)bin1;
    double num2 = *(double *)bin2;
    
    printf("num1 : %lf\nnum2 : %lf\n\n", num1, num2);
    if (num1 == num2) printf("num1 == num2 (built in)\n");
    else printf("num1 != num2 (built in)\n");
    
    int con = 0;
    for (int i = 0; i < 8; i++) 
        if (!(bin1[i] ^ bin2[i])) con = 1;
    if (con) printf("num1 == num2 (bitwise)\n");
    else printf("num1 != num2 (bitwise)\n");
}

But, two NaNs are never equal to each other. One explanation for this could be the fact that there are only 2 versions of infs differing by the first bits while there are 1 + 2^51 different versions of Nans, therefore its unlikely for two NaNs to be equal to each other. But, even when we force two NaNs to be the same in binary they still turn out to be not equal to each other when compared using ==. But, if we compare them using ^^ they are equal.

#include 
int main()
{
    unsigned char bin1[] = {0b00000001, 0b00000000, 0b00000000, 0b0000000, 0b00000000, 0b0000000, 0b11110000, 0b01111111};
    unsigned char bin2[] = {0b00000001, 0b00000000, 0b00000000, 0b0000000, 0b00000000, 0b0000000, 0b11110000, 0b01111111};
    double num1 = *(double *)bin1;
    double num2 = *(double *)bin2;
    
    printf("num1 : %lf\nnum2 : %lf\n\n", num1, num2);
    if (num1 == num2) printf("num1 == num2 (built in)\n");
    else printf("num1 != num2 (built in)\n");
    
    int con = 0;
    for (int i = 0; i < 8; i++) 
        if (!(bin1[i] ^ bin2[i])) con = 1;
    if (con) printf("num1 == num2 (bitwise)\n");
    else printf("num1 != num2 (bitwise)\n");
}

Why is that, what is the reason behind the two different rules for infs and NaNs and how are they implemented in C? Does C check whether any of the two number is NaN before doing any comparison every time?

c floating-point bit-manipulation