-4

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; 
}
Alexis King
  • 43,109
  • 15
  • 131
  • 205
Snoviet
  • 3
  • 1
  • 1
    See previous question, there are lots of others: http://stackoverflow.com/questions/7937789/how-does-the-c-code-that-prints-from-1-to-1000-without-loops-or-conditional-stat – Weather Vane Apr 22 '15 at 19:20
  • This looks like an program that would print stdin in reverse, though it would probably stack overflow for any large inputs. – Alexis King Apr 22 '15 at 19:23

2 Answers2

2

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.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
0

It is a recursive function that echoes in the reverse order entered by the user characters until the end of file key combination will be pressed.

The first enetered character will be outputed last because between its input and output there is next call of main

   if (( c = getchar() ) != EOF) {
        main();
        printf("%c", c);
   }

So this porgram simulates a stack.

Here is a similar program that outputs the name of the program file in the reverse order

#include <stdio.h>

int main( int argc, char *argv[] ) 
{
    if ( *argv != NULL && **argv != '\0' )
    {
        char c = *( *argv )++;
        main( argc, argv );
        printf( "%c", c );
    }

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335