Cannot assign value to global array in c++

让人想犯罪 __ 提交于 2019-12-02 10:29:30

问题


I've got this code:

 #include <iostream>
    int tabela[1];
    tabela[0] = 1;
    int main(){
        std::cout << tabela[0];
        std::cin.get();
        return 0;
    }

and it doesn't want to work. My compiler says " "tabela" doesn't name a type". However if I do this:

#include <iostream>
int tabela[1];
int main(){
    tabela[0] = 1;
    std::cout << tabela[0];
    std::cin.get();
    return 0;
}

It works. Can sb explain me why? Thanks in advance.


回答1:


At the outermost level, a C++ file is a sequence of declarations. tabela[0] = 1; is not a declaration - it's a statement (in particular an expression-statement). A function body, however, is a sequence of statements, so it's fine to put this line inside the body of main (or any other function).

Some statements are declarations (called declaration-statements), but in general they're not.




回答2:


for it to be valid C++, you can only initialize variables in global, you can't assign them there.

edit: comments beat me to it. props



来源:https://stackoverflow.com/questions/26026799/cannot-assign-value-to-global-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!