Differentiate between int main and int main(void) function in C


int main represents that the function returns some integer even ‘0’ at the end of the program execution. ‘0’ represents the successful execution of a program.

The syntax of int main is as follows −

int main(){
   ---
   ---
   return 0;
}

int main(void) represents that the function takes NO argument. Suppose, if we don’t keep void in the bracket, the function will take any number of arguments.

The syntax of int main(void) is as follows −

int main(void){
   ---
   ---
   return 0;
}

Actually, both seem to be the same but, int main(void) is technically better as it clearly mentions that main can only be called without any parameter.

Generally, in C language, if a function signature does not specify any argument, that is the function can be called with any number of parameters or without any parameters.

Let’s take the same logic to implement the code for both functions. The only difference is the syntax for these functions.

Example 1

Given below is the C program for int main() function without arguments −

#include <stdio.h>
int main(){
   static int a = 10;
   if (a--){
      printf("after decrement a =%d\n", a);
      main(10);
   }
   return 0;
}

Output

When the above program is executed, it produces the following result −

after decrement a =9
after decrement a =8
after decrement a =7
after decrement a =6
after decrement a =5
after decrement a =4
after decrement a =3
after decrement a =2
after decrement a =1
after decrement a =0

Example 2

Given below is the same program but with int main(void) function −

#include <stdio.h>
int main(){
   static int a = 10;
   if (a--){
      printf("after decrement a =%d\n", a);
      main(10);
   }
   return 0;
}

Output

When the above program is executed, it produces the following result −

after decrement a =9
after decrement a =8
after decrement a =7
after decrement a =6
after decrement a =5
after decrement a =4
after decrement a =3
after decrement a =2
after decrement a =1
after decrement a =0

If we write the same code for int main() and int main(void) we will get an error. This happens because void indicates that the function takes no parameters.

So, try to remove argument 10 in main in the above example and compile. Hence, after rectification the above code will be as follows −

Example

#include <stdio.h>
int main(){
   static int a = 10;
   if (a--){
      printf("after decrement a =%d\n", a);
      main();
   }
   return 0;
}

Output

When the above program is executed, it produces the following result −

after decrement a =9
after decrement a =8
after decrement a =7
after decrement a =6
after decrement a =5
after decrement a =4
after decrement a =3
after decrement a =2
after decrement a =1
after decrement a =0

Updated on: 08-Dec-2023

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements