Why are C character literals ints instead of chars?

后端 未结 12 1003
悲哀的现实
悲哀的现实 2020-11-22 02:24

In C++, sizeof(\'a\') == sizeof(char) == 1. This makes intuitive sense, since \'a\' is a character literal, and sizeof(char) == 1 as d

12条回答
  •  时光取名叫无心
    2020-11-22 03:01

    I remember reading K&R and seeing a code snippet that would read a character at a time until it hit EOF. Since all characters are valid characters to be in a file/input stream, this means that EOF cannot be any char value. What the code did was to put the read character into an int, then test for EOF, then convert to a char if it wasn't.

    I realize this doesn't exactly answer your question, but it would make some sense for the rest of the character literals to be sizeof(int) if the EOF literal was.

    int r;
    char buffer[1024], *p; // don't use in production - buffer overflow likely
    p = buffer;
    
    while ((r = getc(file)) != EOF)
    {
      *(p++) = (char) r;
    }
    

提交回复
热议问题