全局变量好奇心
假设我有一堆将使用 int = Price; 的函数例如。我可以将其设置在 int main 和所有函数之外,以便它们都调用它吗?
例如,这里我在 main 之外调用了 int Price,但会有更多函数使用它。这样可以吗?
int price;
int main()
{
cout << price;
return 0;
}
Say i have a bunch of functions that will be using int = price; for instance. Can i set this outside int main and all the functions so they all call to it?
For example here i called int price outside main but there will be more functions using it. Is this fine?
int price;
int main()
{
cout << price;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
很好,是的。 绝对不推荐。每次都尽量避免全局变量。您还应该初始化变量。
Fine yes. Recommended DEFINITELY not. Try to avoid global variables at every turn. Also you should initialize your variables.
只要
price
变量在您想要使用的地方可见即可。如果您想在另一个“编译单元”(另一个 .c 文件)中使用此变量,则必须在新文件的开头添加:
extern intprice;
,它告诉编译器:它应该使用项目中其他地方声明的price
变量。请注意,强烈建议不要使用全局变量,因为无法控制谁修改变量以及何时修改变量,这可能会导致一些令人讨厌的副作用。
this is fine as long as the
price
variable is visible where you want to use it.if you want to use this variable in another "compilation unit" (another .c file), you will have to put at the beginning of your new file:
extern int price;
, which tells the compiler that it should use theprice
variable declared elsewhere in the project.note that the use of global variable is strongly discouraged, since there is no way to control who modifies the variable and when it does so, which may lead to some nasty side-effects.