Reputation: 63
I've been programming for over 6 years now and i've always avoided using global variables because there is always another way around the problems.
Today, i work on a (big) project, we want to use a dictionnary of mathematical CONSTANTS what will never be modified anywhere. The only problem i seem to find with globals on internet is the fact that if someone overwrites one it could bug out the whole project. But as mine are constants this problem doesnt apply.
(as a second security to avoid people creating a variable with the same name as one of the constants i will probably pack them all in a single global struct)
Does anyone know of problems that still happend using global constants?
Thanks for your answers! :)
Upvotes: 2
Views: 276
Reputation: 60453
The old-fashioned standard way to create a constant in MATLAB is to write a function. For example pi
is a function. It could be written as:
function value = pi
value = 3.14159;
end
Of course we can overwrite the value of pi
in MATLAB, but it is always a local change, it is not possible to affect another workspace.
Upvotes: 2
Reputation: 25140
In MATLAB, your best bet for mathematical constants is to define a class with properties that have the Constant
attribute. This is described in the doc here, and here's the leading example from that page:
classdef NamedConst
properties (Constant)
R = pi/180
D = 1/NamedConst.R
AccCode = '0145968740001110202NPQ'
RN = rand(5)
end
end
This way, the values cannot be overridden. (Note that there's something a little perhaps unexpected in this example - the value of the property RN
changes each time the class is loaded! I personally wouldn't write code like that...)
Upvotes: 3