soniccool
soniccool

Reputation: 6058

Global Variable Curiosity

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;
}

Upvotes: 2

Views: 110

Answers (2)

Adrien Plisson
Adrien Plisson

Reputation: 23303

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.

Upvotes: 1

FailedDev
FailedDev

Reputation: 26940

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

Upvotes: 2

Related Questions