I sometimes see coders that use NULL
as return value of main()
in C and C++ programs, for example something like that:
#include <stdio.h>
int main()
{
printf("HelloWorld!");
return NULL;
}
When I compile this `code with gcc I get the warning of:
warning: return makes integer from pointer without a cast [-Wint-conversion]
which is reasonable because the macro NULL
shall be expanded to (void*) 0
and the return value of main shall be of type int
.
When I make a short C++ program of:
#include <iostream>
using namespace std;
int main()
{
cout << "HelloWorld!";
return NULL;
}
And compile it with g++, I do get an equivalent warning:
warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]
But why do they use NULL
as return value of main()
when it throws a warning? Is it just bad coding style?
NULL
instead of 0
as return value of main()
despite the warning?Returning null is often a violation of the fail fast programming principle. The null can appear due to some issue in the application. The issue can even go to production if the developer has not implemented proper exception handling, which can help quickly detect the issue.
In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.
Returning null Creates More Work An ideal function, like an assistant cook, will encapsulate work and produce something useful. A function that returns a null reference achieves neither goal. Returning null is like throwing a time bomb into the software.
Is it just bad coding style?
Worse. The correct way to indicate that the program finished fine is
#include <stdlib.h>
int main (void)
{
return EXIT_SUCCESS;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With