Assertions

What should happen when pop_int_stack() is called with an empty stack? One possible solution is to assume that this situation will never arise.

Any assumption should be checked; usually through an assert(). In this case:


	#include <assert.h>

	void
	pop_int_stack(
		int_stack	stack
		)
	{
	  assert( len_int_stack(stack) > 0);
	  x_len_int_stack(stack)--;
	}

If pop_int_stack() is called with an empty stack (i.e. with len_int_stack() of 0), the assertion will be false and it will cause the program to fail, after printing out some kind of error message.

Note that assert() should be used for debugging only. It should be used for checking for conditions that are under programmer control, and should never arise. For instance, it should not be used for checking for malloc() returning 0.

assert() is designed for debugging. If the file is compiled with NDEBUG defined, then the assert() goes away. Depending on the project one may choose to ship the production code with the assert() enabled or disabled.

In general the simplest way to produce code with assertions disabled is to use the -DNDEBUG compiler flag.


	cc -DNDEBUG file.c


Next Prev Main Top Feedback