A common error of getchar() function in c language

getchar() should get a character from the name. It happens that there is a char type in the C language, and the following program can easily appear:

# include <stdio.h>

int main (void)
{
    char c;
    while((c = getchar()) != EOF)
    {
        putchar(c);
    }
    return 0;
}

Mainly talk about the following sentence:

while((c = getchar()) != EOF)
First of all, the prototype of the getchar function is: int getchar(void); The meaning of the above while statement is: if the input in the standard input file is not EOF, then execute the loop body. The return value of the getchar function is an int type, but we used the char type to connect, which means that c may not be able to accommodate all possible characters, and may not be able to accommodate EOF.

Therefore, there are two possibilities for the final result: one is that some legal characters are "truncated" and the value is the same as EOF, and the result of this situation is that the copying may stop prematurely. The second case is that EOF may not be obtained, that is, an infinite loop.

In fact, there is another situation: the program works smoothly because of coincidence. why?

Explain this statement well. According to my understanding, it should be: put the return value of the getchar function in the memory space of c, and "truncate" if the memory is not enough. Then compare c to EOF. If c is not EOF, then true. But many compilers don't implement it that way. These compilers do "truncate" the return value of getchar, but it is not c that is compared to EOF, but the return value of the getchar function. I don't know how to achieve it. It may be to use a variable to record the return value of getchar, and then compare it with EOF; it may also be other. If we use the above compiler, then the result is the same as we originally expected. But what if it wasn't? So this is a coincidence. When we use it, we should use int variables to "install" the return value of getchar.

------------------

The content of the article comes from: "C Traps and Defects" Chapter 5.1 P84

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325563079&siteId=291194637