查询全局变量的初始化

时间:2013-05-07 19:28:54

标签: c++ compiler-errors

无法弄清楚此代码为何会出错。

#include<iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
unsigned long long A[102];
A[0]=2;
int main()
{
    cout<<"OK";
}

编译时出错:

prog.cpp:6:1: error: ‘A’ does not name a type

但这很好用。

#include<iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
unsigned long long A[102];
int main()
{
    A[0]=2;
    cout<<"OK";
}

可能是什么原因?

1 个答案:

答案 0 :(得分:2)

A[0]=2;

不是初始化,而是A的第一个元素的赋值。你不能在函数之外做到这一点。

这是初始化,是合法的:

#include<iostream>

unsigned long long A[102] = {2};

int main()
{
    std::cout<<"OK\n";
}

它会将第一个元素设置为2,其余所有元素都设置为0