Assertions are statements used to test assumptions made by programmer. For example, we may use assertion to check if pointer returned by malloc() is NULL or not.
Following is syntax for assertion.
void assert( int expression );
If expression evaluates to 0 (false), then the expression, sourcecode filename, and line number are sent to the standard error, and then abort() function is called.
For example, consider the following program.
Assertion failed: x==7, file test.cpp, line 13 This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
Assertion Vs Normal Error Handling
Assertions are mainly used to check logically impossible situations. For example, they can be used to check the state a code expects before it starts running or state after it finishes running. Unlike normal error handling, assertions are generally disabled at run-time. Therefore, it is not a good idea to write statements in asser() that can cause side effects. For example writing something like assert(x = 5) is not a good ideas as x is changed and this change won’t happen when assertions are disabled. See this for more details.
In C/C++, we can completely remove assertions at compile time using the preprocessor NODEBUG.
The above program compiles and runs fine.
In Java, assertions are not enabled by default and we must pass an option to run-time engine to enable them.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Difference between C and Objective C
- Strict Aliasing Rule in C with Examples
- Difference between cout and puts() in C++ with Examples
- Difference between forward list and list in C++
- Short-Circuiting in C++ and Linux
- Different types of range-based for loop iterators in C++
- Learn C++ Programming Step by Step - A 20 Day Curriculum!
- Difference between C and Dart
- Difference between Sentinel and Counter Controlled Loop in C
- Why do we need reference variables if we have pointers
- What are the differences between C and Embedded C?
- Similarities and Difference between Java and C++
- Macros and its types in C/C++
- Reversed Range-based for loop in C++ with Examples
Improved By : Jaideep Kaiwart