Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why returning NULL from main()?

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?
like image 612
RobertS supports Monica Cellio Avatar asked Jan 31 '20 10:01

RobertS supports Monica Cellio


People also ask

Why do we return null?

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.

Why is my method returning null Java?

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.

Is it good to return null?

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.


1 Answers

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;
}
like image 64
emacs drives me nuts Avatar answered Oct 19 '22 23:10

emacs drives me nuts