|
| 1 | +/* |
| 2 | + * Exercise 7-9. Functions like isupper can be implemented to save space or to |
| 3 | + * save time. Explore both possibilities. |
| 4 | + * |
| 5 | + * Answer: I take it that by saving space the authors mean increasing code |
| 6 | + * compactness and by saving time reducing run time. Implementing isupper() as |
| 7 | + * a macro avoids the overhead associated with calling a function on to the |
| 8 | + * stack memory; thus, we save time. I suppose it could be argued that this |
| 9 | + * saves stack memory as well, but I do not think that is what the authors |
| 10 | + * meant. To save space, we could implement a macro such as IFUPPER that wraps |
| 11 | + * an "if ..." statement around the isupper() function. The result is a |
| 12 | + * one-line code that performs multiple instructions. Moreover, if we avoid |
| 13 | + * using other functions in the wrapping and use nested macros instead, we |
| 14 | + * could save both time and space. The draw back, of course, is that the code, |
| 15 | + * though more readable, it will be full of unconventional idioms. |
| 16 | + * |
| 17 | + * By Faisal Saadatmand |
| 18 | + */ |
| 19 | + |
| 20 | +#include <stdio.h> |
| 21 | +#include <ctype.h> |
| 22 | + |
| 23 | +#define ISUPPER(c) ((c) >= 'A' && (c) <= 'Z') ? 1 : 0 /* saves time */ |
| 24 | +#define TOLOWER(c) ((c)) + 'a' - 'A' /* saves time */ |
| 25 | +#define IFUPPER_TOLOWER(c) if (isupper((c))) (c) = tolower((c)) /* saves space */ |
| 26 | +#define IF_UPPER_TOLOWER(c) if (ISUPPER((c))) (c) = TOLOWER((c)) /* saves time and space */ |
| 27 | +#define IF_UPPER(c,a) (ISUPPER((c))) ? ((a)) : ((c)) /* saves time and space */ |
| 28 | + |
| 29 | +int main(void) |
| 30 | +{ |
| 31 | + int c; |
| 32 | + |
| 33 | + printf("Enter an upper case character: " ); |
| 34 | + c = getchar(); |
| 35 | + |
| 36 | + if (ISUPPER(c)) |
| 37 | + c = tolower(c); |
| 38 | + printf("%c\n", c); |
| 39 | + |
| 40 | + IFUPPER_TOLOWER(c); |
| 41 | + printf("%c\n", c); |
| 42 | + |
| 43 | + IF_UPPER_TOLOWER(c); |
| 44 | + printf("%c\n", c); |
| 45 | + |
| 46 | + printf("%c", IF_UPPER(c, TOLOWER(c))); |
| 47 | + printf("\n"); |
| 48 | + |
| 49 | + return 0; |
| 50 | +} |
0 commit comments