Assertions: Difference between revisions
Content added Content deleted
Line 62: | Line 62: | ||
There is no mechanism to add a custom "message" with your assertion, like in other languages. However, there is a "trick" to do this, by simply logical-AND-ing your condition with a string constant message, like in the following. Since a string constant is guaranteed to be non-NULL (and hence evaluated as True), and since AND-ing with True is an identity operation for a boolean, it will not alter the behavior of the assertion, but it will get captured in the debug message that is printed: |
There is no mechanism to add a custom "message" with your assertion, like in other languages. However, there is a "trick" to do this, by simply logical-AND-ing your condition with a string constant message, like in the following. Since a string constant is guaranteed to be non-NULL (and hence evaluated as True), and since AND-ing with True is an identity operation for a boolean, it will not alter the behavior of the assertion, but it will get captured in the debug message that is printed: |
||
<lang c>assert(a == 42 && "Error message");</lang> |
<lang c>assert(a == 42 && "Error message");</lang> |
||
This trick only works with |
This trick only works with messages written directly in the source code (i.e. cannot be a variable or be computed), however, since the assertion message is captured by the macro at compile-time. |
||
=={{header|C++}}== |
=={{header|C++}}== |