| C Tutorial | Assert | |||
|
main() Multiple Files Prototypes Preprocessor #define #include foo.h vs foo.c #if Multiple #includes -- #pragma once Assert
|
Array out of bounds references are an extremely common form of C run-time error. You can use the assert() function to sprinkle your code with your own bounds checks. A few seconds putting in assert statements can save you hours of debugging.
Getting out all the bugs is the hardest and scariest part of writing a large piece of software. Assert statements are one of the easiest and most effective helpers for that difficult phase.
#include <assert.h> #define MAX_INTS 100 { int ints[MAX_INTS]; i = foo(<something complicated>); // i should be in bounds, // but is it really? assert(i>=0); // safety assertions assert(i<MAX_INTS);
ints[i] = 0; Depending on the options specified at compile time, the assert() expressions will be left in the code for testing, or may be ignored. For that reason, it is important to only put expressions in assert() tests which do not need to be evaluated for the proper functioning of the program...
int errCode = foo(); // yes assert(errCode == 0);
assert(foo() == 0); // NO, foo() will not be called if // the compiler removes the assert()
Want To Know more with Video ??? Contact for more learning: webmaster@freehost7com |
|