Assert() macro

Share your advanced PureBasic knowledge/code with the community.
Trond
Always Here
Always Here
Posts: 7446
Joined: Mon Sep 22, 2003 6:45 pm
Location: Norway

Assert() macro

Post by Trond »

Code: Select all

#Assert = 1

Macro QUOTE
  "
EndMacro

Macro Assert(Expression)
  CompilerIf #Assert
    If Not (Expression)
      MessageRequester("Program Error", "Assert failed at in file '" + #PB_Compiler_File + "' at line " + Str(#PB_Compiler_Line) + "." + #CRLF$ + "Assert: " + QUOTE Expression QUOTE)
      CallDebugger
      End
    EndIf
  CompilerEndIf
EndMacro

Assert(Apple = Orange)
#Assert = 1 enables asserts. To not compile the program with asserts, use #Assert = 0. Then you will have no speed penalty compared to a normal program.
Last edited by Trond on Wed Jun 17, 2009 9:48 am, edited 1 time in total.
User avatar
Octopus
User
User
Posts: 55
Joined: Sat Jun 13, 2009 6:42 am
Location: Munich (Germany)
Contact:

Post by Octopus »

Because of problems e.g. with comparing operators inside of expressions would it not be better e.g. to use:

Code: Select all

If Not (Expression)
instead of:

Code: Select all

If (Expression) = 0
or will the latter work anyway?
Trond
Always Here
Always Here
Posts: 7446
Joined: Mon Sep 22, 2003 6:45 pm
Location: Norway

Post by Trond »

No, you are right.
User avatar
Rescator
Addict
Addict
Posts: 1769
Joined: Sat Feb 19, 2005 5:05 pm
Location: Norway

Post by Rescator »

Here's a variant of Trond's most excellent Assert.

It's piggybacking fully on the Debugger, so if you compile without the debugger then assert is not compiled either.
Likewise, if an assert failure happen it will use the debug output instead of a requester.
And I removed the End, thus allowing you to choose Continue or Kill from the debug menu instead. (assuming you don't have auto kill enabled that is).

Would be cool if this was available as part of the debugger, but this way rocks too, I may actually find a use for this ;)

Code: Select all

Macro QUOTE
  "
EndMacro

Macro Assert(Expression)
 CompilerIf #PB_Compiler_Debugger
  If Not (Expression)
   Debug "Assert: "+QUOTE Expression QUOTE
   Debug "Line "+Str(#PB_Compiler_Line)+" in "+#PB_Compiler_File
   CallDebugger
  EndIf
 CompilerEndIf
EndMacro

Apple=1
Orange=2

Assert(Apple = Orange)
Post Reply