5

我必须为静态变量分配一个从函数中获取的值。我尝试执行以下操作,但我得到初始化元素不是恒定的。

int countValue()
{
return 5;
}

void MatrixZero()
{

 static int count=countValue();
 count++;
 printf("count value %d \n",count);

}


int main()
{
    MatrixZero();
    return 0;   

}
4

3 回答 3

12

因为......好吧......你的静态变量的初始化器不是一个常数。它必须是一个常量表达式。试试这个:

static int count = SOME_VALUE_OUT_OF_RANGE;
if (count == SOME_VALUE_OUT_OF_RANGE) {
    count = countValue();
}

检查它是否已经初始化。

于 2013-02-15T20:04:23.707 回答
7

使用存储说明符声明的变量static必须使用常量表达式进行初始化。

static int count=countValue();

函数调用不是常量表达式。

于 2013-02-15T20:03:16.277 回答
-1
// wenn countValue ein Objekt zurückgibt

static int* count=0;  if(count==0)count=countValue();
于 2016-03-25T19:06:04.137 回答