Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is assert() in C?

Syed Muhammad Ali Mustafa

assert() is a macro (used as a function) in C. assert() statements help to verify the assumptions made by the developer. They are useful when debugging a program.

Library

#include<assert.h>

Declaration

The following is the declaration of assert():

void assert(int exp)

exp: The expression to be evaluated as non-zero (true) or zero (false).

If exp evaluates to zero, assert() sends the error message to stderrstandard error stream in C/C++ and terminates the program by calling abort(). On the other hand, normal execution continues if exp evaluates to non-zero.

Disabling assert()

We can disable assert() statements by defining the NDEBUG macro before including assert.h in the source file.

assert() statements skipped because of NDEBUG

Code

1. Without NDEBUG

#include <stdio.h>
#include <assert.h>
 
int main()
{
    int x = 1;
    assert(x == 1);
    printf("First assert passed");   

    x = 2;
    assert(x == 1);
    // The below line is not printed
    // because assert evaluates to false.
    printf("\nSecond assert passed"); 

    return 0;
}

2. With NDEBUG

#include <stdio.h>
#define NDEBUG
#include <assert.h>
 
int main()
{
  // Both prints will be executed
  // as assert statements are disabled
  int x = 1;
  assert(x == 1);
  printf("First assert passed");   

  x = 2;
  assert(x == 1);
  printf("\nSecond assert passed"); 

  return 0;
}

RELATED TAGS

c

CONTRIBUTOR

Syed Muhammad Ali Mustafa
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring