gtpc2m0e | C/C++ Language Support User's Guide |
This function, which is implemented as a macro, either verifies a condition or else prints a diagnostic message and abnormally ends the program.
Format
#include <assert.h> void assert(int expression);
The assert macro inserts conditional diagnostics into a program. If expression is true (nonzero), the assert macro suppresses the inserted diagnostics. Otherwise, the assert macro prints the diagnostic message and calls the abort function to abnormally end the program.
The diagnostic message has the following format:
Assertion failed: expression, file: filename, line: line-number
The assert macro uses the __FILE__ and __LINE__ predefined names to generate the printed diagnostic message.
Normal Return
None.
Error Return
None.
Programming Considerations
TARGET(TPF) restriction |
---|
For TARGET(TPF), the assert macro relies on the puts function in order to operate. If assert is called and puts has not been implemented, control is passed to the system error routine. |
Examples
In the following example, the assert macro tests the string parameter for a null string and an empty string, and verifies that the length parameter is positive before proceeding.
#include <stdio.h> #include <assert.h> void analyze(char *, int); int main(void) { char *string1 = "ABC"; char *string2 = ""; int length = 3; analyze(string1, length); printf("string1 %s is not null or empty, " "and has length %d \n", string1, length); analyze(string2, length); printf("string2 %s is not null or empty," "and has length %d\n", string2, length); } void analyze(char *string, int length) { assert(string != NULL); /* cannot be NULL */ assert(*string != '\0'); /* cannot be empty */ assert(length > 0); /* must be positive */ }
Output
String1 ABC is not null or empty, and has length 3 Assertion failed: *string != '\0', file: CBC3BA08 C A1, line: 26
Related Information