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

CC++Server Side ProgrammingProgramming

Sometimes we see that there are two types of main function definition. The int main() and int main(void). So is there any difference?

In C++, there is no difference. In C also both are correct. But the second one is technically better. It specifies that the function is not taking any argument. In C if some function is not specified with the arguments, then it can be called using no argument, or any number of arguments. Please check these two codes. (Remember these are in C not C++)

Example

#include<stdio.h>
void my_function() {
   //some task
}
main(void) {
   my_function(10, "Hello", "World");
}

Output

This program will be compiled successfully

Example

#include<stdio.h>
void my_function(void) {
   //some task
}
main(void) {
   my_function(10, "Hello", "World");
}

Output

[Error] too many arguments to function 'my_function'

In C++, both the program will fail. So from this we can understand that int main() can be called with any number of arguments in C. But int main(void) will not allow any arguments.

raja
Published on 03-May-2019 10:48:54
Advertisements