静态Bool数组未按设置初始化

时间:2017-02-20 10:06:13

标签: c++11 static initialization array-initialization

为什么我的静态bool数组未正确初始化?只初始化了第一个 - 我怀疑这是因为数组是静态的。

以下MWE是使用GCC编译的,并且基于我正在编写的函数,我已将其转移到主程序中以说明我的问题。我曾尝试使用和不使用c ++ 11。我的理解是因为这个数组是静态的并初始化为true,所以我应该在第一次输入函数时打印。所以在这个MWE中它应该打印一次。

#include <iostream>

using namespace std;

const int arraysize = 10;
const int myIndex = 1;

static bool firstTimeOverall = true;

int main()
{
    static bool firstCloudForThisClient[arraysize] = {true};
    cout.flush();
    if (firstCloudForThisClient[myIndex])
    {
        cout << "I never get here" << endl;
        firstCloudForThisClient[myIndex] = false;
        if (firstTimeOverall)
        {
            firstTimeOverall = false;
            cout << "But think I would get here if I got in above" << endl;
        }
    }
    return 0;
}

4 个答案:

答案 0 :(得分:1)

您可能需要反转条件以利用默认初始化:

#include <iostream>

using namespace std;

const int arraysize = 10;
const int myIndex = 1;  // note this index does not access the first element of arrays

static bool firstTimeOverall = true;

int main()
{
    static bool firstCloudForThisClient[arraysize] = {}; // default initialise
    cout.flush();
    if (!firstCloudForThisClient[myIndex])
    {
        cout << "I never get here" << endl;
        firstCloudForThisClient[myIndex] = true; // Mark used indexes with true
        if (firstTimeOverall)
        {
            firstTimeOverall = false;
            cout << "But think I would get here if I got in above" << endl;
        }
    }
    return 0;
}

答案 1 :(得分:1)

static bool firstCloudForThisClient[arraysize] = {true};

这会将第一个条目初始化为true,将所有其他条目初始化为false。

if (firstCloudForThisClient[myIndex])

但是,由于myIndex为1且数组索引从零开始,因此会访问第二个条目,该条目为false。

答案 2 :(得分:0)

您只使用array[size] = {true}初始化数组中的第一个元素,如果arraysize变量大于1,则其他元素的初始值取决于平台。我认为这是一种未定义的行为。

如果你真的需要初始化数组,请改用loop:

for(int i=0; i < arraysize; ++i)
firstCloudForThisClient[i] = true;

答案 3 :(得分:0)

您应该访问数组的第一个元素,因此请使用:

const int myIndex = 0;