Send Close Add comments: (status displays here)
Got it!  This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
C: Assertions


1. C: Assertions

2. Assertions
The English word "assert" means to say or claim that something is correct or true (in a logical sense).

A programming assertion is a claim by the programmer that at a certain point in a program, a certain condition should be true.

3. Typical use of assertions
Usually assertions are interspersed throughout the code at appropriate points.

Here assertions are used as a way to test the behavior of functions.

4. Includes
Here are the modules needed for Booleans and assertions.


5. Preprocessor
The C preprocessor expands the following symbols. So "Boolean" types in C can be interpreted as 0 for false and 1 for true since this is done by the C preprocessor.

The type _Bool is a special C type that has rules for how to convert to/from other types (e.g., in a condition in a if, while, etc.).

6. Simple program
Here is the C code.


7. Output
Here is the output of the C code.


8. Example for isOdd
Here is the C code.


9. Output
Here is the output of the C code.


10. Production mode
Assertions are used in debug mode.

To turn assertion checking off, in production mode, use the following at the top of the file.

To ignore assertions in a program, use the following
at the top of the program.
# define NDEBUG

To go back to debug mode, comment out the above line.

11. Counting loop
Here is the code of a loop that counts and outputs values from 0.0 to 1.0, starting at 0.0 and adding 0.1 each iteration.

The loop executes 10 times, so what should the value of x1 be? Here is the output of the C code.

12. Floating point example
Be very careful about making any assertions about floating point numbers when division is involved.

Here is the C code.


13. Output
Here is the output of the C code.


14. Floating point example
Here is the above program with the assertion uncommented - resulting in an error.

Here is the C code.


15. Run time error
Here is the error text of the C code.


16. End of page

17. Multiple choice questions for this page