Global variables are inefficient and. make errors difficult to diagnose
Show older comments
I'm writing code that builds the Vortex Lattice method, but I'm having trouble calling the variables in my Main code. I'm getting the error in the title on every code and I don't understand why.
Accepted Answer
More Answers (1)
Walter Roberson
on 9 Dec 2024
1 vote
The message is a warning, not an error message.
You are getting the warning message because using global variables is the most expensive form of accessing variables. Literally every other possibility is checked before checking whether a variable is a global. That makes accessing global variables relatively slow.
You are also getting that warning message because historically people have found using global variables to be error-prone, and that it can be quite difficult to track down where global variables are changed. They might not be bad when they are set in a single block of code and are read-only in all other blocks of code, but much more typical is that they end up being modified in several places.
Because the use of global variables is slow and error-prone, the editor gives a warning about them. It is an opportunity to reflect upon whether you really need global variables, and upon whether you have taken precautions to ensure that the global variables are being used correctly.
You can turn off the warning. Right-click on the word "global" and select "Suppress Message" and then either "on this line" or "in this file". But turning off the warning... just turns off the warning, without fixing any of the underlying problems.
Categories
Find more on Debugging and Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!