If a variable is needed throughout the program then only I use the global variable otherwise I use the local variable inside function. I have shown two programs in which I am using local and global variables. When both programs run they give the same output.
global variable
local variable
I think it depends on memory resources to use global and local variables. MCU has limited memory as compare to PC. So if we are writing a complex program on PC and we declare all the variables as global variables then maybe it doesn't matter much. But if we are writing a complex program for MCU and we have declared all the variables as global variables so maybe we can have problem because MCU has limited memory.
I'm curious to know when you are writing a very large program with lots of functions, variables. How do you decide whether you will use a local variable or whether you will use a global variable to use limited memory.
It will not be right to make all the variables as global variables and it will not be right to make all the variables as local variables. There should be a good reason to do it
global variable
C:
#include<stdio.h>
int count; // global variable
void foo (void)
{
count = 0;
count++;
printf("%d \n", count);
}
int main ()
{
foo ();
return 0;
}
C:
#include<stdio.h>
void foo (void)
{
int count; // local variable
count = 0;
count++;
printf("%d \n", count);
}
int main ()
{
foo ();
return 0;
}
I'm curious to know when you are writing a very large program with lots of functions, variables. How do you decide whether you will use a local variable or whether you will use a global variable to use limited memory.
It will not be right to make all the variables as global variables and it will not be right to make all the variables as local variables. There should be a good reason to do it