Printing the value of EOF
Asked Answered
A

3

12

In Kernighan and Ritchie (the C programming language):

'Write a program to print the value of EOF'

I wrote:

#include <stdio.h>

main(){

    int c;
    c = getchar();
    if ((c = getchar()) ==  EOF)
        putchar(c);
}

but it doesn't output anything Why?

Argumentative answered 24/5, 2014 at 11:22 Comment(2)
EOF is not a character, therefore putchar(EOF) can do anything. What you want is printf("%d", EOF).Exclosure
putchar(EOF) is defined to mean putchar( (unsigned char)(EOF) ) (C11 7.21.7.3) , so it can't "do anything" as such, it must output some character. Although perhaps that is a non-printable characterBagel
I
19

putchar function prints a character.

But EOF is not a character and is used to indicate the End of a file. So the getchar returns a value which is distinguishable from the character sets so as to indicate there is no more input.

So printing EOF using putchar() wont print any values

printing it as integer

printf("%d",EOF);

gives result -1

Ioves answered 24/5, 2014 at 11:27 Comment(4)
Mine gives a result -1%, why is that the result when everybody is saying "EOF" isn't a character?Donohue
@MichaelElliott EOF is a macro that expands to -1 (which is an integer value with no corresponding character).Bagel
that is, usually to -1 although it might be any negative integer in generalBagel
@MichaelElliott And the % is because you aren't printing a newline \n.Sidneysidoma
B
9

putchar(c) means to output the character which corresponds to c (which is a number) in the character encoding in use (usually ASCII).

There is no character which is encoded as EOF (that's the whole point of EOF).

The stipulation to "print value of EOF" does not mean "print the character whose code is EOF" (since there is none). Instead they most likely mean to print the integer with the same value as EOF on your system.

Bagel answered 24/5, 2014 at 11:25 Comment(0)
S
6

try this:

#include <stdio.h>

int main(){
    printf("EOF: %d\n", EOF);
}

EOF is not a printable char as you expected.

Supplement answered 24/5, 2014 at 11:25 Comment(1)
EOF is not even a characterPreferential

© 2022 - 2024 — McMap. All rights reserved.