2.6 Local Variable
2.6.1 Definition and characteristics
- Definition:
- Local variables are also called "temporary variables", including all variables defined within FC, and variables 09 declared in the TEMP field of PRG and FB. They can only be accessed and modified within the PU where they are defined
- Features:
- Limited Scope: The scope of local variables is limited to the inside of the PU where they are defined, which helps limit the visibility and usage scope of variables, thereby improving the readability and maintainability of the program
- Dynamic Allocation: In some PLC systems, local variables may dynamically allocate storage space when the PU is called, and release it after the PU execution is completed. This means that local variables cannot store data persistently across scan cycles or PU calls
2.6.2 Application Scenario
- Temporary data storage: When data needs to be temporarily stored during PU execution, local variables can be used to save these data. These data no longer need to be retained after the PU execution is completed
- Parameter passing: When calling a subroutine or function block, you can use local variables as input and output parameters to pass data. This helps achieve modular and reusable code design
- Reduce the use of global variables: By rationally using local variables to replace global variables for data processing and transmission, the frequency and complexity of using global variables can be reduced, thereby improving the reliability and maintainability of the program
warning
- Scope restrictions: When using local variables, it is recommended to pay attention to their scope restrictions to avoid program errors caused by accessing or modifying local variables outside the scope
- Storage efficiency: Although local variables provide flexible data storage and processing methods, variable names that are too long may take up more storage space. Therefore, a balance between storage efficiency and readability needs to be considered when naming
- Data initialization: Before using local variables, it is recommended to ensure that they have been correctly initialized to avoid using undefined or uncertain values that may cause program errors. In some cases, the PLC system may automatically initialize local variables, but in some cases manual initialization may be required