1

我正在查看一些代码示例。在 .h 文件中,有以下声明:

外部 int NODATA;

它在许多其他文件中用于没有逻辑值的变量。

是否有必要在其他地方定义它或者可以不定义它?

4

2 回答 2

0

它是如何使用的?如果它是按值使用的,那么它必须在某个地方定义,并且它将采用它在初始化程序中给出的值——默认情况下,0。(当然,它应该是 const。)如果它仅用于地址(即&NODATA),那么它仍然需要在某个地方定义。但是在这种情况下,惯用的约定是使用空指针:(NULL0,或者如果你有 C++11,nullptr),没有理由不这样做,你也不必定义其他任何东西.

于 2013-05-07T15:05:07.200 回答
0

根据您所说的“使用”的意思,它可能在技术上允许不在任何地方定义,但我当然不会称之为良好实践。以下面的(hackish)程序为例。请注意,它使用了新的 C++11 功能,但 的一些用途NODATA也适用于 c++03。

#include <iostream>
using std::cout;
using std::endl;

extern int NODATA;

auto size = sizeof(NODATA);
auto align = alignof(NODATA);

void f(int c = NODATA)
{
    cout << "c=" << c << endl;
}

decltype(NODATA) main()
{
    cout << "size=" << size << endl;
    cout << "align=" << align << endl;

    f(0);

    // above here should all work, below may not depending on 
    // implementation and its optimization settings

    if(false && NODATA)
    {
        cout << "false && NODATA" << endl;
    }
    else if(true || NODATA)
    {
        cout << "true || NODATA" << endl;
    }
    else
    {
        int i = NODATA;
    }

    // this would definitely cause a linker error
    // f();
    // but this may not
    false ? f() : f(1);

    f((NODATA-NODATA) + 2);
    f((NODATA/NODATA) + 2);
    f((4*NODATA)/NODATA);

    int arry[3] = { [0] = 1, [1] = NODATA, [1] = 2 };

    struct {
        int first;
        int second;
        int third;
    } strct = {.first = 1, .second = NODATA, .second = 2};

    return NODATA^NODATA;

    int i = NODATA;
}

尽管这些结构中的一些结构在NODATA任何地方都没有定义(参见http://ideone.com/hyjOxR的示例运行),但我很难想出任何实际使用它们的理由。

但是,根据您的描述,听起来其余文件正在NODATA用于初始化和/或测试其他变量(可能无法全部优化):

#include "NODATA.h"

int aVariableThatIsActuallyUsed = NODATA;

void SomeInitFunc(void)
{
    aVariableThatIsActuallyUsed = 42;
}

int SomeOtherFunc(void)
{
    if(NODATA == aVariableThatIsActuallyUsed)
    {
        throw SomeException();
    }

    aVariableThatIsActuallyUsed--;

    return aVariableThatIsActuallyUsed;
}

如果是这样,则NODATA必须在 C++ 源文件、程序集文件、库或其他地方进行定义。你知道程序编译和运行没有错误吗?

于 2013-05-07T21:53:31.723 回答