/** * experiments - A variety of experiments with operators and precedence. */ // +-------+---------------------------------------------------------- // | Notes | // +-------+ /* Some of the code contained herein is hideously repetitious. Such repetition could be avoided by the use of an appropriate macro. Unfortunately, the expected readers of this code do not yet know macros. */ // +---------+-------------------------------------------------------- // | Headers | // +---------+ #include // For printf #include // For isdigit #include // For atoi // +---------+-------------------------------------------------------- // | Helpers | // +---------+ /** * looks_like_int(str) * Determine if the string looks like an integer. */ int looks_like_int (char *str) { int i = 0; // Skip over leading sign. if ((str[0] == '+') || (str[0] == '-')) ++i; // Consider remaining characters. while (str[i] != '\0') { if (! isdigit (str[i])) return 0; ++i; } // while // We've read through all the characters. It must be an integer. return 1; } // all_digits // +------+----------------------------------------------------------- // | Main | // +------+ int main (int argc, char *argv[]) { int x; // Our input variable. int i; // A counter variable for loops // Verify that there's a command-line argument. if (argc != 2) { printf ("Usage: experiments INT\n"); return 1; } // incorrect number of arguments // Verify that the command-line argument is a number if (! looks_like_int (argv[1])) { printf ("Usage: experiments INT\n"); printf (" %s is not an integer.\n", argv[1]); return 2; } // not an integer // Grab the number x = atoi (argv[1]); // Try the operators with multiple values. for (i = -5; i <= 5; i++) { printf ("%d + %d = %d\n", x, i, x + i); // printf ("%d - %d = %d\n", x, i, x - i); // a // printf ("%d * %d = %d\n", x, i, x * i); // b // printf ("%d / %d = %d\n", x, i, x / i); // c // printf ("%d %% %d = %d\n", x, i, x % i); // d // printf ("%d < %d = %d\n", x, i, x < i); // e // printf ("%d > %d = %d\n", x, i, x > i); // f // printf ("%d <= %d = %d\n", x, i, x <= i); // g // printf ("%d >= %d = %d\n", x, i, x >= i); // h // printf ("%d == %d = %d\n", x, i, x == i); // i // printf ("%d != %d = %d\n", x, i, x != i); // j // printf ("%d = %d = %d\n", x, i, x = i); // k // printf ("%d += %d = %d\n", x, i, x += i); // l // printf ("%d -= %d = %d\n", x, i, x -= i); // m // printf ("%d *= %d = %d\n", x, i, x *= i); // n // printf ("%d /= %d = %d\n", x, i, x /= i); // o // printf ("%d && %d = %d\n", x, i, x && i); // p // printf ("%d || %d = %d\n", x, i, x || i); // q // printf ("%d & %d = %d\n", x, i, x & i); // r // printf ("%d | %d = %d\n", x, i, x | i); // r // printf ("%d ^ %d = %d\n", x, i, x ^ i); // t // printf ("%d << %d = %d\n", x, i, x << i); // u // printf ("%d >> %d = %d\n", x, i, x >> i); // v } // for // And we're done return 0; } // main