Home  >  Article  >  Backend Development  >  Assertions in C/C++

Assertions in C/C++

王林
王林forward
2023-08-26 18:13:021301browse

C/C++ 中的断言

Here we will learn what assertions are in C/C. The C library macro void assert(int expression) allows diagnostic information to be written to the standard error file. In other words, it can be used to add diagnostics to your C program.

The following is the declaration of the assert() macro.

void assert(int expression);

The argument to this assert() is an expression - this can be a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr (the standard error stream that displays error messages and diagnostics) and aborts program execution.

Sample code
#include <assert.h>
#include <stdio.h>
int main () {
   int a;
   char str[50];
   printf("Enter an integer value: ");
   scanf("%d", &a);
   assert(a >= 10);
   printf("Integer entered is %d\n", a);
   printf("Enter string: ");
   scanf("%s", &str);
   assert(str != NULL);
   printf("String entered is: %s\n", str);
   return(0);
}

Output

Enter an integer value: 11
Integer entered is 11
Enter string: tutorialspoint
String entered is: tutorialspoint

The above is the detailed content of Assertions in C/C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete