Can anybody help me explain this question from a past exam paper? When I compile it, it is never satisfied with any input. Also, what is the reason for the self calling main function?
What does the following program do? Justify your answer.
#include <stdio.h>
int main ( void ) {
int c;
if (( c = getchar() ) != EOF) {
main();
printf("%c", c);
}
return 0;
}
The program is satisfied, by the EOF
returned by getchar()
, achieved by entering Ctrl^Z
(Windows console) or Ctrl-D
(Linux). The program will continue to recurse until that happens (unless the stack breaks). After getting EOF
it drops out of all the recursion printing the inputs in reverse order (including a character representing EOF
).
Note that the EOF
typed must be the first keystroke after an Enter
key.