# assert question

## Recommended Posts

derek7    100
when assert fail, what happen? program crash? assert (i>5) when i=3 what happen?

##### Share on other sites
tanzanite7    1410
Just a crazy idea ... why not try it?

##### Share on other sites
dave    2187

Hey bud

You get an exception window come up, telling you where the assert was called from.

Hope that helps,

ace

##### Share on other sites
tanzanite7    1410
What it exactly does depends on the implementation.
Quote:
 Original post by tanzanite7Just a crazy idea ... why not try it?
You realy should just try it.

##### Share on other sites
joanusdmentia    1060
It could do anything from nothing to making your computer burst into flames.... [grin]

More seriously though, it *can* do nothing int release builds (it's an empty #define in that case), or in debug builds it will usually display a message saying that the assert has failed and then terminate the program (sometimes you'll get the option to use your debugger to break where the assert failed).

##### Share on other sites
superpig    1825
Usually it'll pop up an error dialog. However, there's nothing stopping you from writing your own assert handler; it's easy.

At its simplest, you could use something like this:

#define assert(x) if(!(x)) __asm int 3;

That "int 3" will cause the debugger to pause your program as if it had hit a breakpoint so you can investigate exactly why the assertion has failed. (I use a define instead of a function so that it breaks exactly on the assertion, instead of you having to walk back up the callstack).

A more complex form could be a define and a function working together:

#define assert(x) if(ShouldBreak(x, #x, __FILE__, __LINE__)) __asm int 3;bool ShouldBreak(bool success, char* expr, char* filename, int lineno){ if(success) return false; char buf[1024]; snprintf(buf, "An assertion failed in %s line %i:\n\n%s\n\nPress OK to continue or Cancel to debug.", 1024, filename, lineno, expr); return (IDCANCEL == MessageBox(buf, "Assertion failed", MB_OK_CANCEL));}

That would let you ignore the assertion and continue on if you wanted. You could also do things like log the assertion to a file, report it to a server, add one to a counter of the number of times it has been hit, and so on.