You are here:

C/Question

Advertisement


Question
Hello 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

Answer
Hi 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

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joydeep Bhattacharya

Expertise

Ability to solve C and Data Structure problems and puzzles with simple and easy to understand logic.

Experience

C, C++, Java, Data Structure, PHP, Web Designing

Organizations
http://www.scodz.com Designation: webmaster

Publications
http://www.scodz.com

Education/Credentials
Master of Computer Applications

Past/Present Clients
http://analysingc.50webs.com http://www.funforu.com

©2012 About.com, a part of The New York Times Company. All rights reserved.