Saturday, May 22, 2010

What is the effect using global variables in c programming?

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

What is the effect using global variables in c programming?
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.
Reply: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;
Reply:well, it sorta messy
Reply: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().
Reply: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.


No comments:

Post a Comment