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?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 ofmain()
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.
My usual thump: it is not implementaiton-defined whether the compiler allows it; it is implemenation-specific. In the standard, "implemenation-defined" means that the implementation must document what it does.
@PeteBecker I did pause when writing it but went ahead anyway (because “implementation-specific” and similar phrases just sound unnatural). But you’re correct, I’ll change it.
Seems to me that the only reason "implementation-defined" sounds natural is that people are used to seeing it misused. <g>