Search code examples
cparametersprogram-entry-point

main function in C with void and without void


What is the difference between these two programs? The 1st one i am getting 4,3,2,1 and 2nd one is compilation error.

#include <stdio.h> 
int main() 
{ 
    static int i = 5; 
    if (--i){ 
        printf("%d ", i); 
        main(10); 
    } 
} 

and

#include <stdio.h> 
int main(void) 
{ 
    static int i = 5; 
    if (--i){ 
        printf("%d ", i); 
        main(10); 
    } 
} 

Solution

  • When you define a function like this:

    int func() { ... }
    

    It says that the function takes an indeterminate number of arguments and returns an int. So you can legally pass any number of arguments of any type (although you won't be able to access them).

    When you define a function like this:

    int func(void) { ... }
    

    It says that the function takes no arguments. Attempting to pass any arguments to this function will result in a compile time error.

    On a side note, recursively calling the main function is not a good idea. You're better off either calling another function which is recursive or just using a loop.