Computer >> Computer tutorials >  >> Programming >> C programming

C/C++ difference's between int main() and int main(void)


C

In C programming language, if a function signature is not having any parameters then it can take multiple arguments as input but the same is not true with C++. The compilation will fail if arguments are passed to such a function in C++. This is reason int main() and int main(void) are same in C, but int main(void) is better approach, which restricts the user to pass multiple arguments to main function.

Example (C)

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

Output

2 1

Example (C++)

#include <iostream>
using namespace std;
int main() {
   static int counter = 3;
   if (--counter){
      cout << counter;
      main(5);
   }
}

Output

main.cpp: In function 'int main()':
main.cpp:10:13: error: too many arguments to function 'int main()'
main(5);
^
main.cpp:5:5: note: declared here
int main()
^~~~