English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

What can happen in a big c program when we use global variables even though we can use local variables instead of global variables?

2006-09-04 18:28:38 · 5 answers · asked by Rabin 1 in Computers & Internet Programming & Design

5 answers

In a big program with lots of different source files it might happen that you use the same variable name for different variables.

If you are lucky your linker will warn you about this but more likely it will just merge those two variables together.

The effect is that other parts of the program mysteriously overwrite "your" variable.

2006-09-05 04:07:19 · answer #1 · answered by Huh? Duh! 2 · 0 0

They tell you to avoid using global variable as much as you can because it is GLOBAL. It is accessible by any and every portion of your code and this can lead to some sticky situations when it comes to debugging.

Note to bhiravi k:

The x declared in main() is not a global variable. Global variable in C is declared before the main().

2006-09-05 01:34:15 · answer #2 · answered by cantankerous_bunch 4 · 0 0

You should only use Global variables if only required.
once you declare the variable as global its value persists throught the scope of the program.

But if you overwrite the same variable locally the local variable will persist.
suppose,
main()
{
int x;
x = 100;
sum(2,3);
printf("%d",x);
}
function sum(int a,int b)
{
int x;
x = a + b;
printf("%d",x);
}


When you execute the above
The x inside the function gives 5 and in the main program gives 100.
so the output will be 5 and then 100;

2006-09-05 01:38:33 · answer #3 · answered by bhiravi k 3 · 0 0

It's just bad practice. The problem with global variables is that they can be accessed and altered by any function, method, or object in your program. You should set scope to your variables to prevent unwanted parts of the function for changing them and to make it easier to debug and track problems.

2006-09-05 01:32:13 · answer #4 · answered by Richard M 2 · 0 0

well, it sorta messy

2006-09-05 01:30:29 · answer #5 · answered by KH 3 · 0 0

fedest.com, questions and answers