Global variables
Variables defined outside the function are global variables
Global variables have global lifetimes and scopes
They are independent of any function
They can be used inside any function
#include <stdio.h>intFvoid);intGAll = A;intMain () {printf ("GAll in%s function is%d\n", __func__,gall);//Note: The __func__ is the output is which function, the underscore is two consecutive togetherf (); printf ("GAll again in%s function is%d\n", __func__,gall); return 0;}intf () {printf ("GAll in%s function is%d\n", __func__,gall); GAll+=2; printf ("GAll again in%s function is%d\n", __func__,gall); returnGAll;}
- Initialization of global variables
A global variable that does not initialize will get a value of 0
The pointer will get a null value
Global variables can only be initialized with values that are known at compile time
Their initialization occurs before the main function
- Global variables that are hidden
If there is a variable with the same name as the global variable inside the function, the global variable is hidden.
Static local Variables
Adding the static modifier to a local variable definition becomes a static local variable
When the function leaves, the static variable will continue to exist and maintain its value .
The initialization of a static local variable is only done when the function is first entered , and then the value of the function remains last left.
Static local variables are actually special global variables
They are in the same memory area
A static local variable has a global lifetime, and a local scope within the function.
Static here means the local scope (local access)
Functions that return pointers
Returning the address of a local variable is dangerous
Returns the address of a global variable or static local variable is safe
Returns the memory of malloc within the function is secure, but is prone to problems
The best practice is to return the incoming pointer
Tips
Do not use global variables to pass parameters and results between functions
Try to avoid using global variables
Functions that use global variables and static local variables are thread insecure
The End
Thank you!
C Language Learning-global variables, static local variables