Home  >  Article  >  What is the difference between global variables and local variables

What is the difference between global variables and local variables

青灯夜游
青灯夜游Original
2019-06-05 14:51:1527982browse

What is the difference between global variables and local variables

What are local variables?

Local variable (Local Variable) is a variable defined inside the function body, and its scope is limited to the inside of the function body. It will be invalid outside the function body. Calling it again is an error.

Local variables can also be called internal variables. Variables created by an object or a function are usually local variables and can only be referenced internally and cannot be referenced by other objects or functions.

What are global variables?

Global Variable is a variable defined outside all functions. Its scope is the entire program, that is, all source files, including .c and .h files.

Global variables can be created by an object function or anywhere in the program. Global variables can be referenced by all objects or functions in this program.

The difference between global variables and local variables

1. The valid scope is different

Local variables are only valid within the scope of this function, not outside this function These variables cannot be used;

The valid range of global variables is from the location where the variable is defined to the end of the source file.

2. Different memory spaces

Local variables allocate memory space to the variable when the program runs to the function, and release the memory space when the function ends;

Global variables are Memory space is allocated in advance when the program is running, and the memory is released when the program ends.

3. Different usage ranges

Global variables: apply to the entire program file;

Local variables: apply to the statement block or function to which they belong.

The above is the detailed content of What is the difference between global variables and local variables. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does ioc mean?Next article:What does ioc mean?