## how to make a constant global so all packages files use it?

### Ano (view profile)

on 23 May 2017
Latest activity Commented on by Steven Lord

on 23 May 2017

### Jan Simon (view profile)

hello! I would like to define a constant in such a way all my functions in the package folders use it , how can I do it ?? Thank you in advance .

#### 1 Comment

Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 23 May 2017

The MATLAB documentation clearly states "Best Practice: Passing Arguments", which is also trivially easy:

k = 1.234;
myfun(k,...)
other(k,...)
morefun(k,...)

The MATLAB documentation also says "Use global variables sparingly, if at all", which is also what many discussions on this forum also advise: https://www.mathworks.com/matlabcentral/answers/319613-how-to-use-global-variable-as-local-variable

http://blogs.mathworks.com/videos/2010/03/08/top-10-matlab-code-practices-that-make-me-cry/

etc, etc

### Jan Simon (view profile)

on 23 May 2017

As Stephen has explained already, passing variables as arguments is the best practice.

If you have really good reasons to define a constant globally, do not use global, but prefer a dedicated function, which provides the values as struct:

function C = myPackageConstants()
C.g  = 9.81;
C.pi = 3.14159265;
C.VolumeOfHeidelbergBarrel = 221716;  % liter

Then call this from all function as:

C = myPackageConstants;

This is less clear than using arguments. If it is called very often, it might matter that it has a certain runtime overhead. But in opposite to globals, you can be sure that the values are not modified anywhere, such that debugging gets horrible.

Stephen Cobeldick

on 23 May 2017

+1 nice solution

Steven Lord

### Steven Lord (view profile)

on 23 May 2017

Or if it's a single constant that is broadly usable, like pi, make it a function that returns just that one value. The pi function is built-in, but if it were written as a function file it would be just:

function P = pi
P = 3.14159265358979;