← Back to C Course | Chapter 12: Advanced Topics | Lesson 15 of 20

C assert.h

What is Assertion?

An assertion documents an assumption your code is relying on and checks it automatically at runtime, immediately halting the program if that assumption turns out to be false — catching a bug at the exact point it happens rather than letting it silently corrupt data further downstream.

Example: What is Assertion?

c
#include <stdio.h>
#include <assert.h>
int main() {
	int x = 5;
	assert(x > 0);
	printf("Assumption held: %d", x);
	return 0;
}

The assert() Macro

The assert() macro, defined in assert.h, evaluates the expression you give it and, if that expression is false (zero), prints the failing expression along with the file name, function, and line number to stderr and then calls abort() to stop the program immediately.

Example: The assert() Macro

c
#include <stdio.h>
#include <assert.h>
int main() {
	int age = 25;
	assert(age >= 0);
	printf("%d", age);
	return 0;
}

Disabling Assertions (NDEBUG)

Defining the NDEBUG macro before including assert.h turns every assert() call in that file into a no-op, which is the standard way to strip out assertion checks (and their runtime cost) from a release build while keeping them active during development and testing.

Example: Disabling Assertions (NDEBUG)

c
#define NDEBUG
#include <stdio.h>
#include <assert.h>
int main() {
	assert(1 == 2);
	printf("Assertion skipped");
	return 0;
}

Asserting Pointer Validity

Placing assert(ptr != NULL); right before dereferencing a pointer is a fast, self-documenting way to catch a NULL-pointer bug the moment it happens during development, rather than tracking down a mysterious crash that occurs several function calls later.

Example: Asserting Pointer Validity

c
#include <stdio.h>
#include <assert.h>
int main() {
	int x = 5;
	int *ptr = &x;
	assert(ptr != NULL);
	printf("%d", *ptr);
	return 0;
}

Asserting Value Ranges

Wrapping input parameters in something like assert(index >= 0 && index < size); catches out-of-range values immediately at the function boundary, making the function's real assumptions explicit in the code instead of leaving them as an unwritten expectation.

Example: Asserting Value Ranges

c
#include <stdio.h>
#include <assert.h>
int main() {
	int arr[5] = {1,2,3,4,5};
	int index = 2;
	assert(index >= 0 && index < 5);
	printf("%d", arr[index]);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.