Variable declaration GLOBAL vs LOCAL

2016-01-18
2016-01-19
  • shouryapendyala - 2016-01-18

    Are there any pros and cons from performance standpoint? i.e,. does declaring all variables in global cause the task execution to take longer vs local declaration?

     
  • PrinceACP - 2016-01-19

    Global variables are using memory the entire time your program is running. Local variables will only use memory when a corresponding POU is running/being called. So theoretically, from a performance point of view, all your variables being global will slow down execution.

    Most programmers and literature agree to minimise the use of global variables, largely because of how hard it is to debug and trace them. If you are using a global variable in multiple POUs, then to debug you have to follow the variable through each POU to find an issue. If you figure out a smart way to declare variables locally, then you can debug in just that POU, which is much easier.

    I have written programs in my early days that used a lot of global variables. I even used some Goto statements in some C-Programming projects at uni. These solutions I used were flawed, because at the time, they seemed like an easy solution. But in the long run, they cause many issues in debugging and make the code a lot more complex than it needs to be.

    https://en.wikibooks.org/wiki/A-level_C ... _Variables m

     
  • shouryapendyala - 2016-01-19

    Thanks PrinceACP.

    I am aware of the debugging issues and possible complications with global variables. The only thing I was not sure about was the burden on the task cycle. Thanks again for your input.

     

Log in to post a comment.