Home > Article > Backend Development > What is the difference between local variables and global variables of a C++ function?
C The difference between local variables and global variables: Visibility: Local variables are limited to the defining function, while global variables are visible throughout the program. Memory allocation: local variables are allocated on the stack, while global variables are allocated in the global data area. Scope: Local variables are within a function, while global variables are throughout the program. Initialization: Local variables are initialized when a function is called, while global variables are initialized when the program starts. Recreation: Local variables are recreated on every function call, while global variables are created only when the program starts.
In C, there are important differences between local variables and global variables. Understand these The distinction is critical to writing efficient, maintainable code.
Sample code:
void myFunction() { int localVariable = 5; // 局部变量 // ... 使用 localVariable } int main() { myFunction(); // localVariable 无法访问,因为它不在 main() 函数的范围内 }
Sample code:
int globalVariable = 10; // 全局变量 void myFunction() { // ... 使用 globalVariable } int main() { // ... 使用 globalVariable }
Features | Local variables | Global variables |
---|---|---|
Visibility | Limited to the function in which they are defined | Entire program |
Life cycle | During function call | During program running |
Memory allocation | On the stack | In the global data area |
Scope | In the function | In the entire program |
Initialization | When the function is called | When the program starts |
Recreate | Every time the function When called | Only when the program starts |
In the following example , the local variable name
is only used within the greet()
function, and is recreated each time the function is called:
void greet(std::string name) { std::cout << "Hello, " << name << "!" << std::endl; } int main() { greet("John"); greet("Mary"); // 局部变量 name 将重新创建 }
In the following example, the global variable g_count
is visible program-wide and is updated every time the function is called:
int g_count = 0; // 全局变量 void incrementCount() { g_count++; } int main() { incrementCount(); std::cout << "Count: " << g_count << std::endl; // 输出 1 incrementCount(); std::cout << "Count: " << g_count << std::endl; // 输出 2 }
The above is the detailed content of What is the difference between local variables and global variables of a C++ function?. For more information, please follow other related articles on the PHP Chinese website!