C/Question
Expert: Joydeep Bhattacharya - 8/13/2008
QuestionHello i have a few questions if you could help me out. I just wanted to know what is the difference between local and global variables. Also in which situations would you use each variable local and global, and why do most programmers try to avoid using a global variable.
Thank you
AnswerHi Jason
Any variable declared out side the scope of any function is called global variable and one declared inside is called local variable
for example
int globalVar; // global variable
void main()
{
int localVar; //local variable
//localVar is accessible here and globalVar is also accessible here
}
int func()
{
//globalVar is accessible here but not localVar
}
since localVar is declared within the function boundary of main so it is only accessible to the main function and not any other functions. And since globalVar is declared outside(not in the boundary of any function) so it becomes accessible to all.
The main problem with global variables are concurrent access if more than one instance of a program is running one may be reading the data of the global variable where are the other may be modifying it, these only a single instance of the variable maintained for all the instances of the program.
regards
Joydeep Bhattacharya
http://www.scodz.com