+ 3
A simple local variable program
2 Réponses
+ 3
Hello, SHIV RATAN VISHWAKARMA !
Local variables (pedantically, variables with a block region) are available only in the code block in which they are declared.
Global variables (pedantically, variables with a file region (in C) or a namespace area (in C++)) are available at any time after their declaration.
https://www.sololearn.com/learn/1352/?ref=app
https://www.sololearn.com/Course/CPlusPlus/?ref=app
+ 3
Local Variables cannot be accessed by the whole program directly while the global variables can be accessed anywhere in the program after their declaration.
Local variables can only be accessed in the function in which they are declared after their declaration.
So if we want to use the same local variable in another function then we have to send it to that function using parameters
For example,
#include<stdio.h>
int g=0; //this is global
void func();
void main()
{
int l=0; //this is local
g=1; //as g is global so it can be used anywhere and in any function
l=1; //l is local so it can only be used in this function where it is declared
func();
}
void func()
{
printf(" g = %d", g); //g is global so it can be used here
printf("/n l = %d",l); //this is a syntax error because l is local so it cannot be used outside the function in which it is declared
}
// to resolve this error we send the local variable to the function func using parameters.
See the following code :
#include<stdio.h>
int g=0; //this is global
void func( int );
void main()
{
int l=0; //this is local
g=1; //as g is global so it can be used anywhere and in any function
l=1; //l is local so it can only be used in this function where it is declared
func(l); //we have sent the local variable to the function func
}
void func( int local ) //now we can get l's value using the name of local in this function
{
printf(" g = %d", g); //g is global so it can be used here
printf("/n l = %d",local); //now it's not an error
}
But there are other ways to send local variables to functions.
The way I have shown will only pass the value of l to the function func. If you need to also change l's value in func then you pass in a different way....