Home / Language / English / Assert


Many compilers offer an assert() macro. The assert() macro returns TRUE if its parameter evaluates TRUE and takes some kind of action if it evaluates FALSE. Many compilers will abort the program on an assert() that fails; others will throw an exception

 One powerful feature of the assert() macro is that the preprocessor collapses it into no code at all if DEBUG is not defined. It is a great help during development, and when the final product ships there is no performance penalty nor increase in the size of the executable version of the program.

Rather than depending on the compiler-provided assert(), you are free to write your own assert() macro. Listing below provides a simple assert() macro and shows its use.



More Info

An assertion checks a boolean-typed expression that must be true during program runtime execution. The assertion facility can be enabled or disable at runtime.

Assertion statements have two forms as given below

assert expression;

assert expression1 : expression2;

The first form is simple form of assertion, while second form takes another expression. In both of the form boolean expression represents condition that must be evaluate to true runtime.  The expression that has to be asserted runtime must be boolean value.

If the condition evaluates to false and assertions are enabled, AssertionError will be thrown at runtime.

The second form of assertion takes another expression as an argument. This statement is equivalent to

assert expression1 : throw new AssertionError(expression2);


Some examples that use simple assertion form are as follows.

assert value > 5 ;

assert accontBalance > 0;

assert isStatusEnabled();

About Mohammad Khazab

%d bloggers like this: