Search code examples
carraysfloating-pointreturnputs

C Program Prints Unexpected Word. How does this happen?


Does anybody know how this works?

C Program Source:

int main ()
{
    float b[] = {1.143139e+27};
    puts(b);

    return 0;
}

Output:

Fell

Why would this program display "Fell"?


Solution

  • It has to do with the byte representation of 1.143139e+27, which is exactly Fell, but without the terminating nul byte.

    You can do the reverse process, like

    #include <stdio.h>
    
    int main()
    {
        char b[] = {'F', 'e', 'l', 'l'};
        fprintf(stdout, "%g\n", *(float *)b);
    
        return 0;
    }
    

    and even add a terminating nul byte,

    #include <stdio.h>
    
    int main()
    {
        char b[] = {'F', 'e', 'l', 'l', '\0'};
        fprintf(stdout, "%g\n", *(float *)b);
    
        return 0;
    }
    

    which means that changing float b[] = {1.143139e+27};, to float b[] = {1.14314e+27};