checkConstantDefinitionAtTop

Checks whether all constants are defined at the top of the function or script. Constant definitions are allowed to come before or after persistent and global declarations. Similar, constant definitions are allowed to come before or after import statements. Starting in MATLAB R2019b, the arguments block is available. Since no code can come before this block, all constant definitions will automatically come after it. For this check, a variable is considered to be a constant if it meets all of the following criteria:

  • The value is assigned once. Also no elements of the variable are allowed to be altered.

  • The value of the variable does not depend on function calls, including most MATLAB-installed functions. The only MATLAB-installed functions that can be used after which the variable may still be considered a constant are: pi, eps, sqrt, and factorial.

  • The value does not depend on other variables.

  • No dot notation is used to assign the variable. For example, struct field assignments will not be considered constants.

Aside from numbers and the MATLAB-installed functions listed above, several operators and constructs can be used in a variable declaration and it can still be considered a constant:

  • The expression for assigning the value can contain zero or more of the following operators: ^, :,*, /,+and -.

  • The expression can also be a row or column vector and use the transpose operator (').

  • It can contain strings or character vectors (single and double quotes).

Here are some examples of what are considered constants by CC4M:

a = 100;
b = 1 + 3;
c = 1.3e-9;
d = sqrt(2)/2;
e = pi^2;
f = 3 : 2 : 11;
g = "Test";
h = [3, 5, 10]';

The following variable declarations are not considered constants by CC4M:

k(3) = 5;
l = 100; % The value changes on the next line.
l = 200;
m = v + 1; % Where v is not seen as a constant.
n.field = 10;
p = cumsum([3, 5, 8]);

Exemption tag: %@ok<CNDAT>