Search code examples
cwindowseof

EOF in C, what is EOF?


I have some questions about EOF in C.

  1. What is actually EOF? I have read that it is a macro that "expands" to -1. What does this mean? Specifcally what does "expand" mean in this case?

I have this code:

#include <stdio.h>

int main()
{
    int c;
    scanf("%d", &c);
    if (c==EOF){printf("c is EOF");}
    else {printf("C is not EOF");}
}

Output:

1
C is not EOF
    
-1
c is EOF
    
^Z
  1. In the code, if I write -1, I get that this is EOF. But from what I have read, EOF is not really -1, because we can write -1 at the end of a file?

  2. I have read that on windows to get EOF you need to type CTRL+Z. But when I try to type this and press enter in the terminal, nothing happens, as I demonstrate in the last example in the code. What am I doing wrong?


Solution

  • What is actually EOF? I have read that it is a macro that "expands" to -1. What does this mean? Specifically what does "expand" mean in this case?

    It means that it is defined as C macro for example:

    #define EOF -1
    

    What is EOF?

    EOF indicates that the last operation on the file or stream has reached its end.

    The C preprocessor textually replaces occurrences of the EOF in your source code with -1

    Your code is wrong. scanf returns EOF not scans it. It should be:

    int main()
    {
        int c, val;
        c = scanf("%d", &val);
        if (c==EOF){printf("c is EOF");}
        else {printf("C is not EOF");}
    }
    

    But scanf will almost never return EOF unless you provide a special key combination to force it.