Warm tip: This article is reproduced from stackoverflow.com, please click
c c++ null return-value return

Why returning NULL from main()?

发布于 2020-03-29 21:01:52

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?


  • What is the reason to use NULL instead of 0 as return value of main() despite the warning?
  • 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?
Questioner
RobertS supports Monica Cellio
Viewed
23
Konrad Rudolph 2020-01-31 22:30

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.