Avoid using global variables
-
- Posts: 6
- http://meble-kuchenne.info.pl
- Joined: Sat Dec 05, 2020 12:48 am
Avoid using global variables
Is anyone else having this problem? I have a program that is rapidly growing in complexity and would like to avoid using global variables to keep the memory usage down as well as reduce the clutter of global variables. Is there a way to create static variables or some other method to conserve memory while still being able for variables to retain their values on each loop? Thanks!
-
- Valued Contributor
- Posts: 157
- Joined: Wed Dec 02, 2020 7:28 pm
- Has thanked: 64 times
- Been thanked: 58 times
Re: Avoid using global variables
What is your problem? You state you want to avoid global variables, but not clearly what issues you encounter with that effort.
When programming with local variables only you need to take care if the scope of a variable. If you define one in a macro it will only be available in that macro and cease to exist as soon as that macro ends. So as long as your loop is inside a macro the value will be available. As soon as the macro ends and you call the again the values of any local variables in that macro will be lost.
Using static variables will not conserve memory when compared to using global variables so trying to use them is pointless.
By the way, it is good practice to initialize local variables at the start of the macro so you know what their values are. If you don’t a random value might/will appear.
When programming with local variables only you need to take care if the scope of a variable. If you define one in a macro it will only be available in that macro and cease to exist as soon as that macro ends. So as long as your loop is inside a macro the value will be available. As soon as the macro ends and you call the again the values of any local variables in that macro will be lost.
Using static variables will not conserve memory when compared to using global variables so trying to use them is pointless.
By the way, it is good practice to initialize local variables at the start of the macro so you know what their values are. If you don’t a random value might/will appear.