0

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); 
    } 
} 
abinas patra
  • 359
  • 3
  • 21
  • In the second case, which `main()` which takes a parameter are you trying to call? The one you show is not it. – Yunnosch Jan 22 '19 at 18:50
  • If you show the exact full error it will probably tell you more precisely what I mean. – Yunnosch Jan 22 '19 at 18:51
  • 2
    It is a "formality", when you use `(void)` you are explicitly declaring that the function takes no arguments. If you later call `main(10);` of course it complains, you just told it `main` takes no arguments (plus that other little issue about `main` being the entry point for your program...) – David C. Rankin Jan 22 '19 at 18:51
  • Helpful read: https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/ – Yunnosch Jan 22 '19 at 18:53
  • The problem you're encountering is to do with any regular function, not only `main`. – DeiDei Jan 22 '19 at 18:54
  • Can any language-lawyers speak to the legality of declaring `int main()` vs. `int main(int argc, char *argv[])` or `int main(void)`? Does that fall under implementation-defined behavior? – Christian Gibbons Jan 22 '19 at 20:08

2 Answers2

2

The appearance of a solitary void in a parameter list explicitly tells the compiler "this function takes no arguments".

In the first code example, calling main recursively is permitted since there is no argument list, which permits any number of arguments (this may have been changed in a more recent C standard than the one supported by your compiler; I forget the specifics).

Variables declared static are stored in the process' data section rather than in stack memory, so they persist beyond their scope and retain their value across function calls, so i decrements on each call until it reaches zero and your program hits the base case (don't enter the if statement), and terminates.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
2

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.

dbush
  • 205,898
  • 23
  • 218
  • 273