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;
}
Fine yes. Recommended DEFINITELY not. Try to avoid global variables at every turn. Also you should initialize your variables.
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 the price
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.
精彩评论