Why Do We Need to Use 'Int Main' and Not 'Void Main' in C++

Why do we need to use `int main` and not `void main` in C++?

The short answer, is because the C++ standard requires main() to return int.

As you probably know, the return value from the main() function is used by the runtime library as the exit code for the process. Both Unix and Win32 support the concept of a (small) integer returned from a process after it has finished. Returning a value from main() provides one way for the programmer to specify this value.

Difference between void main and int main

The int main() and the void main() all do the same, which is process the main process of the program.

void main() it means that the functions main() does not return a value.

The difference is int main() is the only right way of calling it, since every program, when called, returns an "error message" that the OS interprets, in which case, closing the program with a return 0; tells the process calling your program that it ended without a problem.

Why does c allow main() even when it is not int main() or void main()?

main() is the old K&R style where the int was omitted as the return type defaults to int if not specified (you should specify it). Additionally, empty parentheses is in K&R style to show it takes no arguments.. in C99 this should now be void to indicate such. Empty parentheses means that the function will accept any number of arguments of any type, which is clearly not what you want. So the final result is:

int main(void) { ... }

main() should return int.. convention says a return 0; statement at the end will help indicate to the caller that the program executed successfully - non-0 return values indicate abnormal termination.

A more direct answer to your question would be that main() { ... } works because it's not wrong. The compiler sees that no return type was declared for the main function so it defaults to int. The empty parentheses indicates to it that main takes any number of arguments of any type, which is not wrong either. However, to conform to C99 style/standard, use

int main(void) { ... }

What are the differences between: main(){}, int main(){} and int main(void){}

Your first example uses a feature inherited from the outdated dialect of C which predated the first ANSI(1989) and ISO(1990) standard: namely, that you can write a function which doesn't specify its return type, and in that case the type defaults to int.

In early C, the void keyword and associated type did not exist. When programmers wanted to write procedures ("functions that have a side effect, but do not return anything"), they simulated it using this feature. They wrote a function without any keyword specifying the return type. They allowed the function to execute to it last statement without returning a value (or alternatively, they used return; to exit from the middle without supplying a value), and they wrote the calls to the function such that those calls did not try to use the return value:

parse_input() /* similar to a procedure in Pascal, but fake! */
{
/* ... */
if (condition())
return; /* no value */
/* ... */
/* fall off end here */
}

int main()
{
parse_input(); /* no return value extracted, everything cool! */
return 0;
}

Unfortunately, some programmers also started not caring about the termination status of a program and writing main itself in this procedure style:

main()
{
/* do something */
/* fall off the end without returning a value */
}

(A mixed style also existed: omitting the int declarator but returning an integer value.)

These programs failing to return a value had an indeterminate termination status. To the operating system, their execution could look successful or failed. Woe to the script writer who tried to depend on the termination status of such a program!

Then things took a turn for the worse. C++ came along and introduced void, and it was adopted into C. With the void keyword in C++, one could declare a function that actually returns nothing (and make it an error to have a return; statement in any other kind of function). The dummy programmers who used to write main with no return type got dumber, and started sticking this new-fangled, fresh-out-of-C++ void in front:

void main() /* yikes! */
{
/* do something */
/* fall off the end without returning a value */
}

By this time they had forgotten that when they wrote main(), it actually meant int main(), which made the function have a compatible type with the startup call invoked by the environment (except for the matter of neglecting to return a value). Now they actually had a different function type from the expected one, which might not even be successfully called!

Where things stand now is that in C++ and in the latest C++ standard, main is still required to return an int. But both languages make a concession for the original dummy programmers: you can let execution "fall off" the end of main and the behavior is as if return 0; had been executed there. So this trivial program now has a successful termination status as of C99 and, I think, C++98 (or possibly earlier):

int main()
{
}

But neither language makes a concession for the second-generation dumber programmers (and everyone else who read the C books that those programmers wrote in the 1980's and since). That is, void is not a valid return declarator for main (except where it is documented by platforms as being accepted, and that applies to those platforms only, not to the portable language).

Oh, and allowance for the missing declarator was removed from C in C99, so main() { } is no longer correct in new dialects of C, and isn't valid C++. Incidentally, C++ does have such a syntax elsewhere: namely, class constructors and destructors are required not to have a return type specifier.

Okay, now about () versus (void). Recall that C++ introduced void. Furthermore, though C++ introduced void, it did not introduce the (void) argument syntax. C++ being more rigidly typed introduced prototype declarations, and banished the concept of an unprototyped function. C++ changed the meaning of the () C syntax to give it the power to declare. In C++, int func(); declares a function with no arguments, whereas in C, int func(); doesn't do such a thing: it declares a function about which we do not know the argument information. When C adopted void, the committee had an ugly idea: why don't we use the syntax (void) to declare a function with no arguments and then the () syntax can stay backward compatible with the loosey-goosey legacy behavior pandering to typeless programming.

You can guess what happened next: the C++ people looked at this (void) hack, threw up their arms and copied it into C++ for the sake of cross-language compatibility. Which in hindsight is amazing when you look at how the languages have diverged today and basically no longer care about compatibility to that extent. So (void) unambiguosly means "declare as having no arguments", in both C and C++. But using it in C++ code that is obviously pure C++ never intended to be C is ugly, and poor style: for instance, on class member functions! It doesn't make much sense to write things like class Foo { public: Foo(void); virtual ~Foo(void) /*...*/ };

Of course, when you define a function like int main() { ... }, the function which is defined has no arguments, regardless of which language it is in. The difference is in what declaration info is introduced into the scope. In C we can have the absurd situation that a function can be fully defined, and yet not declared, in the same unit of program text!

When we write main, usually it is not called from within the program, and so it doesn't matter what the definition declares. (In C++, main must not be called from the program; in C it can be). So it is immaterial whether you write int main() or int main(void), regardless of whether you're using C or C++. The thing which calls main does not see any declaration of it (that you write in your program, anyway).

So just keep in mind that if you write:

int main()  /* rather than main(void) */
{
}

then although it is perfect C++ and correct C, as C it has a slight stylistic blemish: you're writing an old-style pre-ANSI-C function that doesn't serve as a prototype. Though it doesn't functionally matter in the case of main, you may get a warning if you use some compilers in a certain way. For instance, GCC, with the -Wstrict-prototypes option:

test.c:1:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes]

Because -Wstrict-prototypes is a darn useful warning to turn on when programming in C, for improved type safety, (along with -Wmissing-prototypes), and we strive to eliminate warnings from our compile jobs, it behooves us to write:

int main(void) /* modern C definition which prototypes the function */
{
}

which will make that diagnostic go away.

If you want main to accept arguments, then it is int main(int argc, char **argv) where the parameter names are up to you.

In C++, you can omit parameter names, so this definition is possible, which serves nicely in the place of main().

int main(int, char **) // both arguments ignored: C++ only
{
}

Since the argument vector is null-pointer-terminated, you don't need argc, and C++ lets us express that without introducing an unused variable:

#include <cstdio>

int main(int, char **argv) // omitted param name: C++ only
{
// dump the arguments
while (*argv)
std::puts(*argv++);
}

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

In C++, there is no difference.


In C, the difference is questionable. Some love to argue that the latter version (the one without void) is technically just a common implementation extension and not guaranteed to work by the standard because of the wording in the standard. However, the standard clearly states that in a function definition an empty set of parameters has a well-defined behaviour: that the function does not take any parameters. Thus such a definition for main matches the following description in the standard:

It [main] shall be defined with a return type of int and with no parameters.

There is, however, a noticeable difference between the two: namely, the version without void fails to provide a correct prototype for the function:

// this is OK.
int main()
{
if (0) main(42);
}

// this requires a diagnostic to be shown during compiling
int main(void)
{
if (0) main(42);
}

Oh, and just to be complete: the void has the following meaning in all function declarators:

(6.7.6.3p10) The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters.



Related Topics



Leave a reply



Submit