Are local variables generally preferred over global?

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
31 replies · 5K views
From all of the replies it appears that the answer is completely contextual - that we can all hopefully agree on. Bottom line in the most general sense is to program to the language's standard and more importantly to your company/industry's standard.
 
Physics news on Phys.org
Coming from a hobbyist programmer.. I learned to code with NO examples except for the "help" section of Qbasic.. it had NO guidelines on how to code properly.. .Somehow, very surprisingly, I wrote some pretty impressive programs which didn't even use subs and functions!.. Just a WHOLE WHACK of global variables, and lots and lots of "GOTO" statements.
Then I started playing with VB6 and VB.net, and had to try to understand other people's code, nevermind code I had written a couple months earlier.

It took years, and I'm not there yet, but I have figured out how to MOSTLY eliminate global variables, use functions, classes, etc and find alternatives to "goto".

For me, there's something that I still will use global variables for.. things like an "abort" or "Cancel" flag variable that gets checked in a nested part of the program but set in the UI thread

It takes a bit of getting used to, but it is best to minimize global variables whenever possible.. There may be exceptions to the rule, but it's best to learn how to follow the rule before learning when it's correct to break it.