First, local variables
variables defined inside a function are internal variables, they are only valid within the scope of the function, that is, only this function can use them, is not available outside of the function, if used, there will be a variable undefined error. These internal variables are called local variables.
Note : Main function Main The amount of variation defined in the Main function is used internally, and the main function cannot use variables defined by other functions. However, different functions can use variables of the same name, and they do not interfere with each other. Special: The formal parameter is also a local variable.
For example:
#include <stdio.h>
void Fun ()
{
int num=10;
num++;
printf ("fun->%d\n", num);
}
int main ()
{
int i=0;
for (i=0;i<10;i++)
Fun ();
return 0;
}
Where num is a local variable defined in the Fun function and only works inside the fun function, the NUM variable defined in the Fun function cannot be used in the main function. Similarly, I is a local variable defined in the main function and is only valid in the main function.
Second, global variables
A variable defined outside a function is a global variable, also known as an external variable. The valid range of global variables starts at the point where the variable is defined and ends at the end of the file.
Note : Generally, try not to use global variables, it will reduce the generality of the program. If the global variable has the same name as a local variable in a source file, the global variable is masked and the local variable works.
For example:
#include <stdio.h>
int num=10,i=0;
void Fun ()
{
num++;
printf ("fun->%d\n", num);
}
int main ()
{
for (i=0;i<10;i++)
Fun ();
return 0;
}
Where num and I are defined as global variables, it is scoped to the end of the program. Both the fun and main functions can use both global variables.
When we write the program, we can use the global variables and local variables reasonably according to the actual situation, but the global variables should be used sparingly, and the use of global variables in some larger programs will reduce the reliability and generality of the program. Because global variables are masked when global variables and local variables have the same name, local variables work at this time.
This article is from the "unintentional persistent" blog, please be sure to keep this source http://10740590.blog.51cto.com/10730590/1698580
Local variables and global variables