Search code examples
cfloating-pointcharacterprecisionsystem-calls

Storing ASCII code point value in a float prevents its interpretation as a character (in C)


float c;
c = 'a';
while (c <= 'z')
{
    write(1, &c, 1);
    c++;
}

write() is data type-agnostic. It should deliver the correct code point values to the terminal. The terminal should then interprete it according to its character encoding scheme (usually UTF-8).

Question Why does this code output a blank line rather than the alphabet? (the goal of this question is to understand the underlying mechanism at work)

What I have checked I printed out the float values of each incremented c. I seemingly always get the correct code point value ( 116.0000000 for 't', 117.0000000 for 'u' etc) I suspect the problem arises from storing the code point values as floats, potentially causing precision loss somehow.


Solution

  • You asked to write the first byte of the float. That does not produce anything useful.


    Let's look at the following program instead:

    char c = 'a';
    write(1, &c, 1);
    
    int i = 'a';
    write(1, &i, 1);
    
    float f = 'a';
    write(1, &f, 1);
    

    First of all, 'a' is an int, and it's equivalent to 97.[1]

    c, i and f will be all be initialized to have the value ninety-seven, but that is represented differently by different types.

    • The char ninety-seven is represented by byte 61 (hex).[1]
    • The int ninety-seven is represented by bytes 61 00 00 00 or 61 00 00 00 00 00 00 00.[1]
    • The float ninety-seven is represented by bytes 00 00 C2 42.[1]

    The subsequent calls to write output the first of these bytes.

    • 61 for the char. Your terminal displays this as an a.[1]
    • 61 for the int. Your terminal displays this as an a.[1]
    • 00 for the float. Your terminal might display this as an empty space.

    1. I'm assuming a modern desktop system.