Have I used the global variable in a wrong way?
Show older comments
Hi !
I have edited some of my functions in a small software app in this way to reduce the workload for me:
- 1) Is giving mass_salt_g a value based on what the temperature is, set mass_salt_g as a global variable in this function nr 1
- 2) Another one is using this global variable to calculate molalitet_salt, also here I have declared the variable mass_salt_g as a global variable as I have to do sine I am using it here.
- Then I am in a new function calling the second function to calculate molalitet_salt
When I run my app, I get error saying “not enough input arguments”
I cannot send all the functions but it is after that I edited my software like this that I got this error. As far as I can, I don’t want to use mass_salt_g as an input because then I have to edit the software many places . Have I used the global variable in a wrong way?
2 Comments
Stephen23
on 13 Jul 2026 at 14:42
"Have I used the global variable in a wrong way?"
Yes.
Steven Lord
on 13 Jul 2026 at 15:34
If your code references a global variable, anyone with access to the global workspace (i.e. any function or anyone with access to the Command Window) would have the ability to affect the behavior of your app. If they do and cause the app to behave unexpectedly, diagnosing the cause of the unexpected behavior can be much more difficult than if you weren't using global variables.
When you use the term "app" do you mean an interactive user interface (in the sense used in this section of the documentation) or do you just mean an application (a collection of functions for programmatic use)?
If the former, rather than using a global variable I'd likely define a property of your app class and reference that property inside the methods inside your app class.
If the latter, the recommendation could vary depending on exactly how your code is architected. Are you passing around a large number of parameters to a large number of functions? Or is it just this one parameter that needs to be shared? Do many functions need to modify the parameter or is it mainly/solely read-only? And when you say that using a different approach would require you to edit "many places" in the software, roughly how big is "many"? Tens of calls, hundreds, thousands, millions, etc.?
Answers (1)
The global variable has to be set to a certain value before it is first used. So as far as I understand your workflow, you can't call molalitaet_salt from your new function before mass_salt_g has been computed in your function nr. 1. And in every function where you compute/change or use mass_salt_g, the statement
global mass_salt_g
must appear.
Categories
Find more on Debugging and Improving Code 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!