Ram
Ram

Reputation: 411

C++ main vs C main

I am reading a document about C++ vs C. The document says C++ is tightly written when compared to C. One instance is, C allows main() function type to be void. On the other hand C++ does not allow that and he gave the below statement from the standard.

In the C++ Standard:

It shall have a return type of int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

int main() { /* … */ }

and

int main(int argc, char* argv[]) { /* … */ }

The C standard says the same but has an additional statement.

If the return type is not compatible with int, the termination status returned to the host environment is unspecified

which indicates that allowing forms that do not return int is intentional.

When you have the statement "type can be implementation-defined" are you not allowing room for the C++ compiler implementation community to allow void as a type?

Upvotes: 4

Views: 9049

Answers (2)

David Heffernan
David Heffernan

Reputation: 612954

C++

It shall have a return type of int, but otherwise its type is implementation-defined.

That means that the return type must be int, but that the parameters to main can be implementation defined. So there is scope for implementation specific parameters to main, but no scope for variation from an int return type.

C

C is more permissive over the allowable return types of main. It does allow return types other than int.

Upvotes: 7

Kerrek SB
Kerrek SB

Reputation: 477030

Both C and C++ require that any implementation of the language must support the forms int main(void) and int main(int, char**). However, the standards also say that additional forms may be supported by the implementation, and thus a program that uses one of those other forms is not automatically invalid -- rather, it is a valid program that only happens to be supported on certain platforms.

The only difference between C and C++ in that regard is which alternative forms of main are permitted. In C++, all forms must return int, so only the arguments are allowed to vary, and moreover, if the first two arguments of any form are int, char**, they should have the usual meaning.

C is a little more liberal, as it allows any alternative form of main. Thus a program with void main(char, double) is a valid C program that requires the implementation to support this signature, while it would unconditionally be ill-formed C++. On the other hand, int main(int, char**, char**) is a permissible signature for both C and C++, also requiring implementation support, and C++ would expect the first two arguments to have the usual meaning.

Upvotes: 14

Related Questions