Videos
What is global variable in C?
Where are Global Variables Stored in C?
Can global variables be constant in C?
As the title states, really. Is there a "preferred" practice of how you declare your variables, or is it all just personal preference?
For instance I currently have a lot of global variables in my code, but they're all used all over the place in many different functions so to me it makes sense for the majority of them to be global. Also, my code is for embedded systems.
From what I can see though, people seem to think it's better to use local variables over global variables, even though this would surely take tons of re declaring and complex function arguments to keep variables across multiple functions.
Am I just not thinking about this the right way? Are there pros and cons of both global and local variables?
Edit: Forgot to mention that the C code is used in Atmel uC's, and is Embedded.
The only way is to hide the declaration of the local variable in a code block.
For example
#include <stdio.h>
int i = 10;
void fun2( void )
{
int i = 20;
printf("local i = %d\n",i);
{
extern int i;
printf( "global i = %d\n",i);
}
}
int main(void)
{
fun2();
}
The program output is
local i = 20
global i = 10
The best way is to pass parameters to the function
void fun2(int fromExternalWorld){
int i=50;
printf("%d ",fromExternalWorld);
printf("%d\n",i);
}
int main(void)
{
fun2(i);
}
Otherwise is not possible to have two symbols with same name visible in the same scope.