Custom Search

07 June 2008

A Pascal version of the assert C macro to aid debugging.

A Pascal version of the assert C macro to aid debugging 1

You can create your own symbol (called DEBUG, say) and have

{$ifdef DEBUG} {$D+} {$else} {$D-} {$endif}

and set both $D and your conditional simultaneously. There's no really clean
way to do Assert in Delphi; the one I prefer is

const
debug = {$ifdef DEBUG} true {$else} false {$endif};

procedure Assert(condition:boolean);
begin
if not condition then {give some error message} ;
end;

Now, to put a call to Assert into your program only while debugging, use

if debug then Assert(X>1);

The call to Assert will be stripped out if debug is false; if you make no
references to Assert that don't get stripped, then the whole routine will be
stripped out of the executable.

>My next question is: is there any trick how to generate the line number
>like in MFC ? Probably not, because of unavailability of macro, am I right ?

No, there's no way I know of. You can call Runerror() to generate a run-time
error and print the address; you could write a program to search through a
..map file to find that address, or just ask the IDE to do the search for you
(with Find Error).

No comments: