Let's do a quick example. Say you are implementing quick sort. In particular, you are trying to validate your partition method. You can insert an assertion to make sure that your partition method is functioning as expected, as below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
#include <vector> | |
using namespace std; | |
// check if partitioned array[start:pivot] and array[pivot+1:end] | |
bool isPartitioned(vector<int>& array, int start, int pivot, int end) { | |
for (int i=start; i<pivot; i++) | |
if (array[i] > array[pivot]) return false; | |
for (int i=pivot+1; i<end; i++) | |
if (array[i] <= array[pivot]) return false; | |
return true; | |
} | |
// partition array[start:end] | |
int partition(vector<int>& array, int start, int end) { | |
int pivot = start; | |
int i = start+1; | |
int j = end - 1; | |
while (true) { | |
while (i < j && array[i] <= array[pivot]) i++; | |
while (array[j] > array[pivot]) j--; | |
if (i >= j) break; | |
swap(array, i, j); | |
} | |
swap(array, j, start); | |
assert(isPartitioned(array, start, j, end)); | |
return j; | |
} |
In fact, both C/C++ and Java has a nice way to disable and enable the entire assertion statements. For C/C++, you simply need to define a macro NDEBUG, which will disable all assertions. Otherwise, assertions are enabled by default, unless of course you define NDEBUG macro in your source files explicitly. Therefore, you need disable assertions at compile time for production binary:
$ g++ *.cpp -DNDEBUG
Here, -D is the option for implicit #define macro, so the option -DNDEBUG will define NDEBUG macro for all files.
For Java, there is -da and -ea options which will disable and enable assertions, respectively at the runtime. In fact, assertions are by default disabled in Java, so you need to enable with -ea option when debugging, as below:
$ java -ea SomeClass
For more info, please refer to this and this official documentations.
Happy coding!
No comments:
Post a Comment