局部静态变量初始化问题
在C中对静态变量初始化必须使用常量,但最近偶然遇到一个问题,在C++中竟然可以使用变量初始化静态变量。我对C++不熟悉,这是C++的一个特性吗,C++标准上有说明吗?
以下的测试程序是在保证语义不变的情况下的实例
// For C ---> Error
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int test(void)
{
static int a = rand(); // ---> Error, initializer is not a constant
return ++a;
}
int main(void)
{
int i;
srand((unsigned)time(NULL));
for (i = 0; i < 10; ++i)
{
printf("%d\n", test());
}
return 0;
}
// For C++ ---> OK
#include <iostream>
#include <ctime>
using namespace std;
int test(void)
{
static int a = rand(); // ---> OK, why not error
return ++a;
}
int main(void)
{
srand((unsigned)time(NULL));
for (int i = 0; i < 10; ++i)
{
cout << test() << endl;
}
return 0;
}