main function in C with void and without void

1276 views c
4

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); 
    } 
} 

answered question

In the second case, which main() which takes a parameter are you trying to call? The one you show is not it.

If you show the exact full error it will probably tell you more precisely what I mean.

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...)

The problem you're encountering is to do with any regular function, not only main.

1 Answer

7

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).1

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.

1: Not a duplicate, but this question may be of interest to you, OP and readers: Function call with more parameters than expected.

posted this

Have an answer?

JD

Please login first before posting an answer.