C assert() Macro Tutorial

In this section, we will learn what the assert() function is and how it works in C.

What is assert? assert() Macro in C

The `assert()` macro is used in a critical location in a program to check whether a certain condition is true. If the condition wasn’t true, the program should be terminated and that’s what the `assert()` function does.

This function-like macro is in the `assert.h` header file and so we need to include the file in order to use it.

assert() Macro Syntax

void assert(int expression);

assert() Macro Parameters

This macro takes as its argument an expression that either evaluates to true or false. If the expression resulted true, the function won’t do anything. But if the result was false, it will cause the function to terminate the program and send an error to the output stream.

assert() Macro Return Value

The function does not return a value.

Example: using assert() macro in C

#include <stdio.h>
#include <assert.h>
int main() {

   int i ;
   printf("Please enter a value larger than 10:\n");
   scanf("%d",&i);
   assert(i>10);
   printf("The value is: %d", i);
    return 0;
}

Output:

Please enter a value larger than 10:

100

The value is: 100

In this example, the value of the `i` variable is checked against number 10 in the call to the `assert()` macro. If the value is greater than 10, then the condition is true and the program will continue running the instructions after the call to the `assert()` function.

But if the result of the call to the `assert()` was false, the program will terminate immediately, as the example below shows:

#include <stdio.h>
#include <assert.h>
int main() {

   int i ;
   printf("Please enter a value larger than 10:\n");
   scanf("%d",&i);
   assert(i>10);
   printf("The value is: %d",i);
    return 0;
}

Output:

Please enter a value larger than 10:

3

Assertion failed!

Program: H:\c-workstation\ cmake-build-debug\untitled15.exe

File: H:\c-workstation\ main.c, Line 8

Expression: i>10
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies