Testing some string properties using the assert() C function

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: Testing some string properties using the assert() C function

To show: The assert() C function usage

 

#include <stdio.h>

#include <assert.h>

#include <string.h>

 

// function prototype

void TestString(char *string);

 

void main(void)

{

// first test array of char, 10 characters, should be OK for the 3 test conditions...

char test1[] = "abcdefghij";

// second test pointer to string, 9 characters, should be OK for the 3 test conditions...

char *test2 = "123456789";

// third test array char, empty, should fail on the 3rd condition, cannot be empty...

char test3[] = "";

printf("Testing the string #1 \"%s\"\n", test1);

TestString(test1);

printf("Testing the string #2 \"%s\"\n", test2);

TestString(test2);

printf("Testing the string #3 \"%s\"\n", test3);

TestString(test3);

}

 

void TestString(char * string)

{

// set the test conditions, string must more than 8 characters...

assert(strlen(string) > 8);

// string cannot be NULL

assert(string != NULL);

// string cannot be empty, test3 should fail here and program abort...

assert(string != '\0');

}

 

Output example:

 

Testing the string #1 "abcdefghij"

Testing the string #2 "123456789"

Testing the string #3 ""

Assertion failed: strlen(string) > 8, file f:\vc2005project\myaddr\myaddr\myaddr.cpp, line 32

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index