Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is a simple assertion in C language?
An assertion is a statement used to declare positively that a fact must be true when that line of code is reached. Assertions are debugging tools that help catch programming errors during development by validating expected conditions.
Syntax
assert(expression);
Where expression is a condition that should evaluate to true. The assert() macro is defined in the assert.h header file.
How Assertions Work
- True condition: When the expression is true, the program continues normally with no action.
- False condition: When the expression is false, the program terminates and displays an error message with file name, line number, and the failed expression.
-
Disabled assertions: In release builds, assertions can be disabled by defining
NDEBUGbefore includingassert.h.
Example: Basic Assertion Usage
The following example demonstrates how assertions work with valid and invalid input −
#include <stdio.h>
#include <assert.h>
int main() {
int x = 10;
int y = 5;
/* This assertion will pass */
assert(x > y);
printf("x (%d) is greater than y (%d) - assertion passed
", x, y);
/* This assertion will also pass */
assert(x + y == 15);
printf("Sum assertion passed: %d + %d = %d
", x, y, x + y);
/* This assertion will fail and terminate the program */
assert(x < y);
printf("This line will not be executed
");
return 0;
}
x (10) is greater than y (5) - assertion passed Sum assertion passed: 10 + 5 = 15 Assertion failed: xExample: Array Bounds Checking
Assertions are commonly used to validate array indices and prevent buffer overflows −
#include <stdio.h> #include <assert.h> void printArrayElement(int arr[], int size, int index) { /* Assert that index is within valid bounds */ assert(index >= 0 && index < size); printf("Element at index %d: %d
", index, arr[index]); } int main() { int numbers[] = {10, 20, 30, 40, 50}; int size = 5; /* Valid access */ printArrayElement(numbers, size, 2); /* This will cause assertion failure */ printArrayElement(numbers, size, 10); return 0; }Element at index 2: 30 Assertion failed: index >= 0 && indexKey Points
- Assertions should be used for debugging and catching programming errors, not for handling expected runtime errors.
- Never use assertions for user input validation as they can be disabled in release builds.
- Assertions help make code self-documenting by explicitly stating assumptions.
- Good assertion placement includes checking function parameters, array bounds, and invariant conditions.
Conclusion
Simple assertions in C provide an effective debugging mechanism to catch programming errors early. Use assert() to validate assumptions and conditions that should always be true during program execution.
