C preprocessor: Difference between revisions
→Uses
[unchecked revision] | [unchecked revision] |
(See discussion - deserves the disputed tag) |
(→Uses) |
||
Line 25:
{{stub}}
=== Uses ===
==== assert() ====
Assertions are used to catch situations which should never happen, even under error circumstances. If the condition given in the parantheses does not evaluate to "true", a diagnosis is printed which contains source file name, line number, and (since C99) name of the current function; the program then calls abort().
<source lang="c">
#include <assert.h>
assert( sizeof(struct free_memory_block) == 8 );
assert( 1 != 2 );
assert( gdt_ptr != null );
</source>
For production code, assertions may be turned off by defining NDEBUG:
<source lang="bash">
gcc -DNDEBUG ...
</source>
Note that <assert.h> does not have (or need) a header guard, i.e. can be included multiple times in a source file, and that whether NDEBUG is defined or not is evaluated anew ''at every inclusion of <assert.h>''. You can thus enable / disable assertions at a very fine-grained level if necessary:
<source lang="c">
#include <assert.h>
/* assert() at this point only fails-on-false if NDEBUG is not defined */
assert( isChecksumCorrect() );
#ifdef NDEBUG
/* Hard-enabling of assert() even if NDEBUG is defined */
#define NDEBUG_WAS_SET
#undef NDEBUG
#include <assert.h>
#endif
/* assert() in this block of code should fail-on-false even in production */
assert( isChecksumCorrect() );
#ifdef NDEBUG_WAS_SET
/* Restoring NDEBUG if it was enabled originally */
#define NDEBUG
#include <assert.h>
#endif
</source>
==== Disabled Code ====
Sometimes you want to disable a section of code. However, if the code already contains /* C-style comments */, using those very same comments is not an option because they do not nest. The preprocessor provides an easy way around:
<source lang="c">
#if 0
/* disabled code */
...
#endif
</source>
If you want to enable the code section only ''temporarily'', replace the '#if 0' with '#if 1'. Using '#else' it is even possible to have alternative code sections (e.g. for testing).
=== Hazards of the C preprocessor ===
|