Assert In C

Example

void assert( int expression);

The function requires an expression as its parameter, which is then assessed. In case the evaluated result of the expression is 0 or FALSE, an error is generated containing the expression, file name, and execution line. Should errors arise, the program invokes the abort function. On the other hand, if the expression evaluates to TRUE, the assert function does not take any action.

Implementing assert in a Program

To integrate the assert function into your program, it is essential to include the assert.h header file within your program.

Example

#include <stdio.h>
#include <assert.h> 
int main()
{int constt = 100;
// The portion contains multiple lines of code
// Assuming that some operations have been performed in the code
// that have changed the value of constt from 100 to 10.
constt = 10;
// the programmer is unaware of these changes
// and assumed that the value of constt is still 100.
assert(constt==100);
//code after assertion.
return 0;
}

Output:

In the code snippet provided, an assertion is triggered due to the false condition, resulting in the failure of the assertions.

Assert vs Error Handling in C Programming

Programmers employ assertions to validate conditions that are logically incorrect. They are implemented in situations where programmers aim to verify the code's state before proceeding with program execution. These scenarios are logically impossible.

Error handling occurs at runtime, while the assert statement does not execute during runtime. It is recommended to avoid utilizing the assert statement in your code execution to prevent any potential adverse effects during runtime.

Ignore the Assertions in your Program

As previously mentioned, the assert statement can potentially lead to side effects at compile time, making it challenging to eliminate all assertions from the code due to the laborious nature of the task.

In C programming, there exists a simpler technique to entirely eliminate all assert statements from your code at runtime.

It is done using the preprocessor NDEBUG.

Below is the code implementing assert while using the NDEBUG:

Example

#include <cassert>

#ifdef NDEBUG
#define assert(condition) ((void)0)
#else
#define assert(condition) \
    if (!(condition)) \
    { \
        std::cerr << "Assertion failed: " #condition " in file " << __FILE__ \
                  << " on line " << __LINE__ << std::endl; \
        std::terminate(); \
    }
#endif

int main() {
    int x = 5;
    assert(x == 5); // This assertion will pass

    int y = 10;
    assert(y == 5); // This assertion will fail

    return 0;
}
Example

// The program return below will not through any error because we have //defined the pre-processor NDEBUG in it.
#define NDEBUG
# include <assert.h>
int main()
{
int constant = 10;
assert (constant==1);
return 0;
}

Output:

Input Required

This code uses input(). Please provide values below: