A recursive main function

In languages such as C, there is a privileged function - main - that is the entry point for execution. Running the program is tantamount to calling main, which in turn calls other functions.

Since main is a name in the global namespace, there is nothing to prevent it from calling itself. Consider this recursive main function that calculates the factorial:

main.c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

  static int acc = 1;

  if (argc < 2) {
    printf("error: need argument\n");
    return 0;
  }

  int n = atoi(argv[1]);

  if (n <= 1) {
    printf("%d\n", acc);
    return 1;
  } else {
    acc = n * acc;
    sprintf(argv[1], "%d", --n);
    return main(argc, argv);
  }
}

main takes two inputs. argc is the number of command line arguments, and argv is an array of those arguments. The library function atoi converts a string to the integer it represents, and sprintf prints to a string rather than standard output. So we decrement n with each recursive call until the base case is reached, and print out the result. The accumulator acc is a static variable, which means it persists across function calls.

Here is an example output:

$ gcc main.c
$ ./a.out 5
120

The fact that this programs works is convincing evidence that main, other than being the entry point, is an ordinary function that can be called from another part of the code, including from itself.