Lesson – 2

Lesson – 2

Difference between “int main()” and “int main(void)” in C/C++?

rn

Consider the following two definitions of main().

rn

int main()
{
/* */
return 0;
}
Run on IDE
and

rn

int main(void)
{
/* */
return 0;
}

rn

What is the difference?

rn

In C++, there is no difference, both are same.

rn

Both definitions work in C also, but the second definition with void is considered technically better as it clearly specifies that main can only be called without any parameter.
In C, if a function signature doesn’t specify any argument, it means that the function can be called with any number of parameters or without any parameters. For example, try to compile and run following two C programs (remember to save your files as .c). Note the difference between two signatures of fun().

rn

Consider the Following:

rn

// Program 1 (Compiles and runs in C, but not in C++)
void fun() { }
int main(void)
{
fun(10, “FACE”, “PRP”);
return 0;
}

rn

The above program compiles and runs fine, but the following program fails in compilation

rn

// Program 2 (Fails in both C and C++)

rn

void fun(void) { }
int main(void)
{
fun(10, “FACE”, “PRP”);
return 0;
}

rn

Unlike C, in C++, both of the above programs fails in compilation. In C++, both fun() and fun(void) are same.

rn

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.

rn

If you had missed the first lesson click here.

rn

Follow this profile to not miss out on the daily lessons.

rn

 

c