Nivetha Chezhian Nivetha Chezhian - 15 days ago 6
C Question

Passing int argument to the main function

I found the following code here as an example for explaining the arguments given to the main function.The output is 4 3 2 1.What exactly is the parameter 10 passed to the main() does?
Thank you.

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

Answer

Quoting the article that you posted:

So the difference is, in C, int main() can be called with any number of arguments, but int main(void) can only be called without any argument. Although it doesn’t make any difference most of the times, using “int main(void)” is a recommended practice in C.

calling main(10) is just demonstrating that without void as a parameter you can pass anything to a function

For example

Try executing that code but instead include main(10,11,11) and note that the output is the same even though you are passing more arguments to main.

But then try passing it to this:

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

This is simply identifying that putting void in a method that takes no arguments is best practice.

Comments