in c the return value for main() is optional why in c++ the main() must return value ?
sanjay
Hi sanjay
C and C++ have different ANSI standards. Both require an int to be returned from main() but the compiler will allow void in C. The runtime environment still expects an int to be returned so anything could happen. In C++ the compiler will fail if anything other than an int is declared. This is part of C++ standards.
In both C and C++ main MUST return int. Not doing so invokes undefined behaviour (it just happens that in many cases that the undefined behaviour is everything works as expected which is a possible outcome of undefined behaviour).
Undefined behaviour is a bad thing to invoke as anything could happen, the compiler is at liberty to create any code it chooses.
As willakawill states C++ compilers are just better at detecting this error but it does not mean that it is not an error in C.
main should be declared as
int main(int argc, char **argp);
In C99 and C++ you also have the option of declaring it as
Comment