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 subsequent calls to write output the first of these bytes.


    1. I'm assuming a modern desktop system.