Asserting Conditions - C++

Sometimes, certain operations can be dangerous. They can corrupt memory, freeze your computer, or worse. Normally, you know what must be true in order for the operation to succeed. You know that certain conditions must be true. If these conditions are not true, the results could be disastrous. It is your duty, as a programmer, to test for these conditions before proceeding with the operation. If the condition fails, you must immediately end the program or risk catastrophe.

Okay, that was a little melodramatic. It’s true that some operations can cause problems, but it is rare for them to be permanent or disastrous. However, to make your program execute successfully, it is a good idea to test to be sure that conditions are true before performing a major operation (or a potentially risky one). If a condition fails while you are testing your program, you might simply exit the program and have the program display a message saying what happened and on which line.

C++ provides a special macro, called an assertion, for exiting the program and displaying a specified message for a specified condition. Assertions are macros that test a condition and exit the program if the condition fails. A standard version of this macro is defined in <cassert> and <assert.h> header files. The prototype for an assertion is as follows:

cerr behaves exactly like cout, except that it is used for reporting errors. It is included with <iostream>. The code #a converts the failed condition into a string. The code __LINE__ and __FILE__ return the line number and filename, respectively.

Here is an example of how you might use this macro:

The preceding code uses a for statement to initialize all the elements of an array. However, before i is used as an index, you use an assertion to make sure that i is within the bounds of the array.

You can use assertions, as in the previous example, to ensure that you don’t walk off the end of an array. You also use them at the beginning of functions to ensure that the user applied the function correctly, and you use them to validate the result of code that you are not sure is correct.

Keep in mind that you use assertions to debug code, so before you release something or give it to other people to use, be sure to remove all the assertions. (The users of your program do not need to know that an assertion failed on line 675 of a code file.) If you want to handle unexpected errors happening in your program when you release it, use exception handling.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C++ Topics