2

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;
}
soniccool
  • 5,790
  • 22
  • 60
  • 98

2 Answers2

2

Fine yes. Recommended DEFINITELY not. Try to avoid global variables at every turn. Also you should initialize your variables.

FailedDev
  • 26,680
  • 9
  • 53
  • 73
  • But syntactically speaking its fine right? Because i needed to use it for what i did. – soniccool Oct 09 '11 at 20:25
  • @mystycs Syntactically speaking it is correct. But what you did I am sure it can also be done without global variables. By initializing I mean to whatever value you deem correct whether is is 0 or something else, regardless the fact that most modern compilers do this for you. It is considered and is a best practice. – FailedDev Oct 09 '11 at 20:27
  • Also global variables also have a nasty habit of name clashing – Ed Heal Oct 09 '11 at 20:34
1

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.

Adrien Plisson
  • 22,486
  • 6
  • 42
  • 73