C++ 如何在函数内部声明全局变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20847418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:21:41  来源:igfitidea点击:

How to declare global variable inside function?

c++variablesloopsglobalmain

提问by user3137147

I have problem creating global variable inside function, this is simple example:

我在函数内部创建全局变量时遇到问题,这是一个简单的例子:

int main{
   int global_variable;  //how to make that
}

This is exactly what I want to do:

这正是我想要做的:

int global_variable;
int main{
                   // but I wish to initialize global variable in main function
}

回答by Joseph Mansfield

You have two problems:

你有两个问题:

  1. mainis not a loop. It's a function.

  2. Your function syntax is wrong. You need to have parentheses after the function name. Either of these are valid syntaxes for main:

    int main() {
    }
    
    int main(int argv, const char* argv[]) {
    }
    
  1. main不是循环。这是一个函数。

  2. 您的函数语法错误。您需要在函数名称后加上括号。这些中的任何一个都是以下的有效语法main

    int main() {
    }
    
    int main(int argv, const char* argv[]) {
    }
    

Then, you can declare a local variable inside mainlike so:

然后,您可以在内部声明一个局部变量,main如下所示:

int main() {
  int local_variable = 0;
}

or assign to a global variable like so:

或分配给一个全局变量,如下所示:

int global_variable;

int main() {
  global_variable = 0;
}

回答by sasha.sochka

There is no way to declareit the way you want. And that's it.

没有办法按照你想要的方式声明它。就是这样。

But:

但:

  • First, if you want you can declare it before the mainbody but assign a value to it inside main. Look Paul's answer for that
  • Second, actually there is no advantage of declaring variables the way you want. They are globaland that means they should be declared in the globalscope and no other places.
  • 首先,如果你愿意,你可以在mainbody之前声明它,但在main. 看看保罗对此的回答
  • 其次,实际上按照您想要的方式声明变量没有任何优势。它们是全局的,这意味着它们应该在全局范围内而不是在其他地方声明。

回答by Boldijar Paul

int global_variable;
int main()
{
               global_variable=3; // look you assigned your value.
}

回答by General Chaos

well... its indirectly possible by declaring pointers global, and later assigning local variables to them, but sometimes it may lead to situations where pointed variable is unaccessible .

嗯……通过声明全局指针,然后将局部变量分配给它们,间接可能是可行的,但有时可能会导致无法访问指向变量的情况。