/** * utest_swap.c - unit tests for the swap procedure. */ #include #include #include "array_utils.h" // +-----------+------------------------------------------------------ // | Constants | // +-----------+ /** The size of the array we use for testing. */ #define SIZE 32 /** The starting values of that array. */ #define START -10 // +-----------+------------------------------------------------------ // | Variables | // +-----------+ /** * A count of errors. */ static int errors = 0; // +---------+-------------------------------------------------------- // | Helpers | // +---------+ /** * A quick test of swap. */ static void test_swap (int a[], int i, int j) { int x = a[i]; int y = a[j]; swap (a, i, j); if (a[i] != y) { printf ("After swapping positions %d and %d, " " expected %d at %d but found %d.\n", i, j, y, i, a[i]); ++errors; } if (a[j] != x) { printf ("After swapping positions %d and %d, " " expected %d at %d but found %d.\n", i, j, x, j, a[j]); ++errors; } } // test_swap // +------+----------------------------------------------------------- // | Main | // +------+ int main () { int values[SIZE]; int i, j; // Fill in the array for (i = 0; i < SIZE; i++) values[i] = i + START; // Try swapping every pair of positions for (i = 0; i < SIZE; i++) { for (j = 0; j < SIZE; j++) { // We swap the values and then swap them back again. test_swap (values, i, j); test_swap (values, i, j); } // for j } // for i // And we're done if (errors) { printf ("%d errors encountered.\n", errors); return EXIT_FAILURE; } else { return EXIT_SUCCESS; } } // main