Why returning NULL from main()?

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;
}

When I compile this `code with gcc I get the warning of:

warning: return makes integer from pointer without a cast

This is because you compile with lax compiler options. Use strict C standard settings -std=c11 -pedantic-errors and you will get the expected compiler error, on implementations where NULL expands to the null pointer constant (void*)0. See “Pointer from integer/integer from pointer without a cast” issues.

On implementations where NULL expands to 0, the code is strictly speaking standard compliant, but very bad style, non-portable and worst of all: complete nonsense.

And compile it with g++, I do get an equivalent warning:

warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]

On C++11 and beyond, NULL shouldn't be used - instead use nullptr. To return it from main() is incorrect regardless. NULL always expands to 0 in C++ so strictly speaking it will work, but it is very bad style and worst of all: complete nonsense.

Is it just bad coding style?

Not just bad, but nonsense coding style without any rationale. The programmer who wrote it was incompetent.


which is reasonable

Yes.

because the macro NULL shall be expanded to (void*) 0

No. In C++ the macro NULL must not expand to (void*) 0 [support.types.nullptr]. It may only do so in C.

Either way, writing code like this is misleading since NULL is supposed to refer to the null pointer constant, regardless of how it’s implemented. Using it in place of an int is a logical error.

  • What is the reason to use NULL instead of 0 as return value of main() despite the warning?

Ignorance. There is no good reason to do this.

  • Is it implementation-defined if this is appropriate or not and if so why shall any implementation would want to get a pointer value back?

No, it is never appropriate. It is up to the implementation whether the compiler allows it. A conforming C++ compiler may well allow it without warning.


In ?some/many/all? C++ implementations NULL is a macro expanded to 0.

This when expanded in effect gives return 0. Which is a valid return value.

Is it just bad coding style?

Yes.