# int main() vs void main() vs int main(void) in C & C++

May 30, 2017 131054

## The difference between int main() and int main(void)

Both int main() and int main(void) may look like same at the first glance but there is a significant difference between the two of them in C but both are same in C++.

In C, a function without any parameter can take any number of arguments. For example, a function declared as ‘foo()’ can take any number of arguments in C (calling foo(), foo(1), foo(‘A’,1) will not give any error).

#include <stdio.h>

void foo()
{}

int main()
{
foo();
foo(1);
foo(1,'A');
foo(1,'A',"ABC");
printf("ABC\n");
return 0;
}


The above code runs fine without giving any error because a function without any parameter can take any number of arguments but this is not the case with C++. In C++, we will get an error. Let’s see.

#include <iostream>

using namespace std;

void foo()
{}

int main()
{
foo(1);
cout << "ABC" << endl;
return 0;
}


Running the above code will give us an error because we can’t pass any argument to the function ‘foo’.

However, using foo(void) restricts the function to take any argument and will throw an error. Let’s see.

#include <stdio.h>

void foo(void)
{}

int main()
{
foo(1);
printf("ABC\n");
return 0;
}


The above code will give us an error because we have used ‘foo(void)’ and this means we can’t pass any argument to the function ‘foo’ as we were doing in the case of ‘foo()’.

So, both foo(void) and foo() are same in C++ but not in C. The same is the case with ‘main’ function also. So, the preferred form to use is int main(void) if main is not taking any argument.

## Difference between int main() and void main() and main()

Like any other function, main is also a function but with a special characteristic that the program execution always starts from the ‘main’. ‘int’ and ‘void’ are its return type. So, let’s discuss all of the three one by one.

• void main – The ANSI standard says "no" to the ‘void main’ and thus using it can be considered wrong. One should stop using the ‘void main’ if doing so.
• int main – ‘int main’ means that our function needs to return some integer at the end of the execution and we do so by returning 0 at the end of the program. 0 is the standard for the “successful execution of the program”.
• main – In C89, the unspecified return type defaults to int. So, main is equivalent to int main in C89. But in C99, this is not allowed and thus one must use int main.

So, the preferred way is int main.

Liked the post?
Developer and founder of CodesDope.
Editor's Picks
1 COMMENT