当前位置:网站首页>Global variable vs local variable

Global variable vs local variable

2022-06-26 13:41:00 Tom looks at programming

1. Global variables

Global variables : Global variables can be referenced by all objects or functions in this program

 

extern usage :

The right solution : Use extern Key words to Statement Variables are external variables . Specifically, in one of them c In file Definition A global variable key, Then in the other to use key Of this variable c Use... In the document extern keyword Statement once , This indicates that this variable is an external variable , Is in the other c Global variables defined in the file . Please pay attention to the words I use here : Definition and Statement . For example, in main.c Variables defined in file key, stay common.c Declaration in the document key Variables are external variables , In this way, this variable can be shared between the two files key 了 , As shown in the figure below .

   The code is as follows ( Write only the part related to the problem we are talking about ):

  (1)main.c file

  #include "common.h"
  unsigned char key;

  (2)common.c file :

  #include "common.h"
  extern unsigned char key;

   Many people may be confused after reading it , Here's a little , In fact, that is Variable definitions and Variable declarations The difference between , Variable definitions Use “ data type + Variable name ” In the form of , The compiler needs to allocate memory units to it ; and Variable declarations Use “extern Variable type + Variable name ” In the form of , Is to tell the compiler that this variable will be external to others c The document defines , I only use it externally here . The compiler doesn't allocate memory space to it , Wait until you really encounter the variable definition, and then allocate memory space for it .

2. local variable

local variable : local variable , Also called internal variables , A variable defined inside a function or a compound statement . local variable The scope of is the function that defines the variable or the compound statement that defines the variable . local variable The lifetime of the function is calculated from the time when the function is called to the time when the function returns to the call

 

The local variables in the two functions do not affect each other , It's not relevant at all .

Citations :C Language extern effect ( Global variables ) - Creamy onion - Blog Garden (cnblogs.com)

原网站

版权声明
本文为[Tom looks at programming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170513412778.html