
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Assertions in C and C++
What is an Assertions in C/C++?
An assertion is a statement used to test assumptions made by the program. When an assertion fails, the program displays an error and stops. This is mainly used for debugging.
In C and C++, assertions are handled using the assert()
macro defined in the
Following is the declaration for assert() Macro.
#include// in C // or #include in C++ assert(expression);
The parameter of this assert() is expression: This can be a variable or any C/C++ expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr (standard error stream to display error messages and diagnostics) and aborts program execution.
When to Use Assertion?
We can use the assertion in the following conditions:
- To check for conditions that should never happen.
- To catch programming errors early during development.
- To validate function preconditions/postconditions.
C Assertion Example
Following is the c example, demonstrating the use of assertions to validate user input at runtime. It ensures that the entered integer is greater than 10 and the string is not null. If the condition is false then the program terminates with an assertion failure error ?
#include <assert.h> #include <stdio.h> int main() { int a = 15; char str[] = "tutorialspoint"; // Assert that a is at least 10 assert(a >= 10); printf("Integer value is: %d\n", a); // Assert that the string is not empty assert(str[0] != '\0'); printf("String value is: %s\n", str); return 0; }
Following is an output of the above code ?
Integer value is: 15 String value is: tutorialspoint
C++ Assertion Example
This is cpp example, to demonstrate the assertions. It ensures that the divisor is not zero. If the divisor is zero then the program terminates with an assertion failure error ?
#include <iostream> #include <cassert> using namespace std; int divide(int a, int b) { assert(b != 0); // Make sure divisor is not zero return a / b; } int main() { int result = divide(10, 2); cout << "Result: " << result << endl; result = divide(5, 0); cout << "Result: " << result << endl; return 0; }
Above code generates the following output ?
Result: 5 main.o: /tmp/eeqd0wb3BZ/main.cpp:6: int divide(int, int): Assertion `b != 0' failed. Aborted