fbpx

C++: Assertions

Bjarne-stroustrup
 

Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point.

Show an assertion in your language by asserting that an integer variable is equal to 42.

#include <cassert> // assert.h also works

int main()
{
	int a;
	// ... input or change a here

	assert(a == 42); // Aborts program if a is not 42, unless the NDEBUG macro was defined
	// when including <cassert>, in which case it has no effect
}

SOURCE

Content is available under GNU Free Documentation License 1.2.