[fpc-pascal] Proper preprocessor?

Sven Barth pascaldragon at googlemail.com
Fri Jun 22 07:24:21 CEST 2018


Am 22.06.2018 um 06:35 schrieb Ryan Joseph:
> Here’s a macro I like from C. It captures the assert expression and prints it back out into the console (it would halt the program also). Can this be done in Pascal? In C they return the file name and line number also which is really nice.
>
> {$define assert(x):=if not (x) then writeln('assert: x')}
>
> var
> 	i: integer = 100;
> begin
> 	assert(i = 101); // assert: i=101
> end.
That directly can't be done, but Assert() in Pascal is nice (and quite 
powerful) nevertheless:

=== code begin ===

program ttest;

{$Assertions on}

var
   i: LongInt;
begin
   i := 42;
   Assert(i = 21, 'Bla, Blubb');
end.

=== code end ===

This will print:

=== output begin ===

Bla, Blubb (ttest.pp, line 9).

=== output end ===

If $Assertions is set to Off the complete Assert() line will be absent 
from the compiled code.

If unit SysUtils is included then a failed assertion results in an 
EAssertionError though that can be changed by setting AssertErrorProc in 
unit System. If unit System is not included then the line above will be 
printed and the program terminated.

Regards,
Sven



More information about the fpc-pascal mailing list