关于c ++:为什么从main()返回NULL?

Why returning NULL from main()?

我有时会看到在C和C ++程序中使用NULL作为main()的返回值的编码器,例如:

1
2
3
4
5
6
7
8
#include <stdio.h>

int main()
{
    printf("HelloWorld!");

    return NULL;
}

当我用gcc编译此代码时,得到以下警告:

warning: return makes integer from pointer without a cast [-Wint-conversion]

这是合理的,因为宏NULL应扩展为(void*) 0,并且main的返回值应为int类型。

当我制作一个简短的C ++程序时:

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main()
{
    cout <<"HelloWorld!";

    return NULL;
}

并使用g ++进行编译,我得到了等效的警告:

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

但是,为什么当它们发出警告时,为什么使用NULL作为main()的返回值呢? 这只是不好的编码风格吗?

  • 尽管有警告,还是使用NULL而不是0作为main()的返回值的原因是什么?
  • 它是否是实现定义的,是否合适?如果是,为什么任何实现都希望返回指针值?


which is reasonable

是。

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

否。在C ++中,宏NULL不得扩展为(void*) 0 [support.types.nullptr]。它只能在C语言中这样做。

无论哪种方式,编写这样的代码都会产生误导,因为NULL应该被引用为空指针常量,而不管其实现方式如何。用它代替int是逻辑错误。

  • 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?

不,永远都不适合。编译器是否允许它取决于实现。合格的C ++编译器可能会毫无警告地允许它。


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

1
warning: return makes integer from pointer without a cast

这是因为您使用松散的编译器选项进行编译。使用严格的C标准设置-std=c11 -pedantic-errors,在NULL扩展为空指针常量(void*)0的实现上,您将得到预期的编译器错误。请参阅"来自整数的指针/没有转换的指针的整数"问题。

NULL扩展为0的实现中,代码严格来说符合标准,但是样式非常糟糕,不可移植且最糟糕的是:完全废话。

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

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

在C ++ 11及更高版本上,不应该使用NULL-而是使用nullptr。无论如何,从main()返回它都是不正确的。 NULL在C ++中始终会扩展为0,因此严格来说它可以工作,但这是非常糟糕的样式,最糟糕的是:完全废话。

Is it just bad coding style?

不仅不好,而且没有任何理由的废话编码风格。编写它的程序员不称职。


Is it just bad coding style?

更差。指示程序完成正常的正确方法是

1
2
3
4
5
6
#include <stdlib.h>

int main (void)
{
    return EXIT_SUCCESS;
}


在"部分/许多/全部"中? C ++实现NULL是扩展为0的宏。

实际上展开时,将给出return 0。这是有效的返回值。

Is it just bad coding style?

是。