/* * stdlib_test — verifies that SDCC's z80.lib stdlib functions (atoi, * strtol, rand, qsort, bsearch, abs, ldiv) work in our environment. * If they all behave correctly, we can save ourselves the labour of * reimplementing them in libc/stdlib. */ #include #include #include static int cmp_int(const void *a, const void *b) { int ia = *(const int *)a; int ib = *(const int *)b; return (ia > ib) - (ia < ib); } int main(int argc, char **argv) { /* atoi / strtol */ int v_atoi = atoi("12345"); long v_strtol = strtol("-9876", NULL, 10); long v_hex = strtol("ff", NULL, 16); printf("atoi(\"12345\") = %d (expected 12345)\n", v_atoi); printf("strtol(\"-9876\",,10) = %ld (expected -9876)\n", v_strtol); printf("strtol(\"ff\",,16) = %ld (expected 255)\n", v_hex); /* abs / ldiv */ printf("abs(-7) = %d (expected 7)\n", abs(-7)); { ldiv_t q = ldiv(100L, 7L); printf("ldiv(100,7) = {q=%ld, r=%ld} (expected {14, 2})\n", q.quot, q.rem); } /* rand / srand — deterministic with fixed seed */ srand(42); printf("rand x3 (seed 42): %d %d %d\n", rand(), rand(), rand()); /* qsort */ { int arr[] = { 5, 1, 4, 2, 8, 3, 7, 6, 0, 9 }; qsort(arr, 10, sizeof(int), cmp_int); printf("qsort:"); for (int i = 0; i < 10; i++) printf(" %d", arr[i]); printf(" (expected 0..9 sorted)\n"); /* bsearch */ int key = 7; int *p = (int *)bsearch(&key, arr, 10, sizeof(int), cmp_int); printf("bsearch(7) -> %s (expected found)\n", (p && *p == 7) ? "found" : "MISS"); } /* argv-as-int: typical CLI use */ if (argc > 1) { printf("argv[1] as int: %d\n", atoi(argv[1])); } puts("\nall SDCC stdlib functions reachable."); return 0; }