Search code examples
ccharactergetcharnul

Why getchar() works int these two cases differently?


I am writing little program for encoding characters and I have a problem with reading NUL characters maybe also with another ones. My problem is that getchar in this code somehow ignores the NUL characters entered by CTRL + @ .

while ((numberOfRead < 40) && (character = getchar()) && (character != EOF) && (character != '\n')) { ... }

But this code works correctly and reads the NUL characters properly.

character = getchar();
while ((numberOfRead < 40) && (character != EOF) && (character != '\n')) {
    numberOfChars++;
    ...
    character = getchar();
}

What is the difference causing the problem? Thanks for any explanation of this behaviour. Code was tested on Windows 8.1, under gcc 4.7.1


Solution

  • Here:

        while (... && (character = getchar()) && ...) ...
    

    you use the value of character as truth value. When the read character is the null character with the value 0, this condition is false.

    You can do something like:

        while (numberOfRead < 40
           && (character = getchar()) != EOF && character != '\n') { ... }
    

    but I find your second variant with the getchar outside the condition more readable.