Assertions for debugging

Use only in the MuPAD Notebook Interface.

This functionality does not run in MATLAB.




The statement assert(cond) declares that the condition cond holds true at the moment when the statement is evaluated. By default, MuPAD® does not care about assertions. After setting testargs(TRUE), however, MuPAD checks every assertion and stops with an error if boolean evaluation of cond does not give TRUE.

Assertions are a major debugging tool for programmers: by stating frequently what they think to have achieved, programmers make it easy for themselves to detect the first unintended intermediate result.


Example 1

Suppose we want to write a function f that takes an integer as its argument and returns 0 if that integer is a multiple of 3, and 1 otherwise. One idea how to code this could be the following: given an integer n, n modulo 3 must be equal to one of - 1, 1, or 0. In any case, abs(n mod 3) should do what we want:

f := proc(n: DOM_INT): DOM_INT
local k: DOM_INT;
  k := n mod 3;
  assert(k = 1 or k = -1 or k = 0);

Checking assertions is switched on or off using testargs:

oldtestargs := testargs(): testargs(FALSE): f(5)

The result does not equal 1. For debugging purposes, we switch on assertion checking:

testargs(TRUE): f(5)
Error: Assertion 'k = 1 or k = -1 or k = 0' has failed. [f]

This shows that the local variable k must have gotten a wrong value. Indeed, when writing our program we overlooked the difference between mod and the symmetric remainder given by mods.




A boolean expression

Return Values

assert returns TRUE or raises an error.

See Also

MuPAD Functions

Was this topic helpful?