A. Global variables
• defined outside of the function variables are global
• Global variables have a global scope and lifetime
• They have nothing to do with any function
• they can be used in any internal function
II. Global variables are initialized
• do not initialize global variables get a value of 0
• pointer will get a NULL value
• Use only with known values compile-time to initialize global variables
• their initialization occurs before the main function
#include <stdio.h> int f(void); int gAll = 12; int main(int argc, char const *argv[]) { printf("in %s gAll=%d\n",__func__,gAll); //__func__打印函数名字 f(); printf("agn in %s gAll=%d\n",__func__,gAll); return 0; } int f(void) { printf("in %s gAll=%d\n",__func__,gAll); gAll +=2; printf("agn in %s gAll=%d\n",__func__,gAll); return gAll; }
Hidden global variables
• If there is an internal function variables and global variables of the same name, then the global variables are hidden
III. Static local variable
• The local variables defined in the plus static modifier becomes static local variable
• When leaving the function of static local variable will continue to exist and retain their value
• initialize static local variable is only the first time you enter this function to do, the future will hold value when you left when entering the function
• static local variable is actually a special global variables
• They are located in the same area of memory
• static local variable with global survival, local scope within the function
• static here means local scope (locally accessible)
#include <stdio.h> int f(void); int gAll =12; int main(int argc,char const *argv[]) { f(); // f(); // f(); return 0; } int f(void) { int k =0; static int all =1; printf("&gAll=%p\n",&gAll); printf("& All =% the p-\ the n- " , & All); // static local variable is actually a special global variables printf ( " & k =% the p-\ the n- " , & k); printf ( " in% S All =% d \ the n- " , __ __ FUNC, All); All + = 2 ; the printf ( " AGN in% S% All D = \ n- " , __ __ FUNC, All); return All; }
IV. * Return pointer function
• Returns the local address of a variable is dangerous
• return the global variable or static local variable address is safe
• Return malloc function in the memory is safe, but likely to cause problems
• The best practice is to return the incoming pointer
#include <stdio.h> int *f(void); void g(void); int main(int argc, char const *argv[]) { int *p= f(); printf("*p=%d\n",*p); g(); printf("*p=%d\n",*p); return 0; } int *f(void) { int i=12; printf("&i=%p\n",&i); return &i; } void g(void) { int k=24; printf("&k=%p\n",&k); printf("k=%d\n",k); }
Tips
• Do not use global variables to pass parameters and results between function
• Try to avoid using global variables
• Toyota's case
• * function using global variables and static local variable is disturbed by a thread