From Lazarus wiki
Revision as of 12:11, 11 February 2021 by Kai Burghardt (talk | contribs) (create)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The compiler procedure assert inserts an assertion. This is a procedure requiring the Boolean value true in order to proceed, otherwise a run-time error is generated.


The procedure assert has the following signature:


The passed parameter has to be true to continue program flow. Usually this is an expression.

By default the FPC has code generation for assertions disabled. That means, invocations of assert do not end up in the generated binary, thus have no effect whatsoever. By specifying the local compiler directive {$assertions on} (or {$C+} for short) or specifying the ‑Sa command-line switch, appropriate code for assertions is inserted.


If the first parameter is false, the assertErrorProc procedure is called. This is by default a procedure generating the RTE 227 “Assertion failed error”. In order to convey more information, the assert procedure accepts a second optional short string parameter:

assert(Boolean, shortstring)

The second parameter’s value is passed to the current assertErrorProc. The default handler prints the message to standard error.


Note: The sysUtils unit installs an assertErrorProc handler generating an eAssertionFailed exception.


Assertions are a straightforward concept ensuring certain statements hold true. However, they do not guarantee your program is indeed correct.

Assertions are frequently used during development. For example, in the following operator overload the assertion ensures certain properties about the operation:

operator - (const positive: foo): foo;
	result := negation(foo);
	assert(sum(positive, result) = neutralElementOfAddition);

However, checking this over and over again is not necessary in a production program. This is a decision that has to be made on a per-application-basis, sometimes on a per-assertion basis.

Although assert is usually provided with a non-trivial Boolean expression, constants are allowed too. In the following piece of code the programmer used an assertion to ensure there is always one alternative taken.

case  of
		assert(false, 'one case has to match!');

Throwing an exception would have been overkill, since usually either a, b or c is in fact the case.

the power of 10 suggest two assertions minimum per function.

Assertions are not used to verify that the compiler works:

procedure foo(var bar: toot);
	assert(assigned(@bar)); // wrong

see also