K&R C Programs Exercise 4-14

Exercise 4-14. Define a macro swap(t,x,y) that interchanges two arguments of type t. (Block structure will help.) A three-argument swap macro: t is the type, x and y are the variables to swap. The block { … } creates a local scope for the temporary, preventing name leakage. The conventional temp variable name _swap_tmp (with …

K&R C Programs Exercise 4-12

Exercise 4-12. Adapt the ideas of printd to write a recursive version of itoa; that is, convert an integer into a string by calling a recursive routine. K&R’s printd (Section 4.10) prints a number recursively: recurse on n/10 to print all leading digits first, then putchar(n%10 + ‘0’) on the way back up. itoa must …

K&R C Programs Exercise 4-11

Exercise 4-11. Modify getop so that it doesn’t need to use ungetch. Hint: use an internal static variable. In the original calculator, getop calls ungetch once: when it reads a non-digit character to terminate a number, it pushes that character back so the next call to getop will see it. The fix: instead of pushing …

K&R C Programs Exercise 4-10

Exercise 4-10. An alternate organization uses getline to read an entire input line; this makes getch and ungetch unnecessary. Revise the calculator to use this approach. The original calculator reads the input one character at a time via getch/ungetch. This exercise replaces that machinery with a line-buffer approach: read the whole line into a static …

K&R C Programs Exercise 4-9

Exercise 4-9. Our getch and ungetch do not handle a pushed-back EOF correctly. Decide what their properties should be if an EOF is pushed back, then implement your decision. The bug: K&R’s original implementation uses char buf[BUFSIZE]. When ungetch(EOF) is called, EOF (typically -1) is stored as char. On platforms where char is unsigned, -1 …

K&R C Programs Exercise 4-6

Exercise 4-6. Add commands for handling variables. (It’s easy to provide for twenty-six variables with single-letter names.) Add a variable for the most recently printed value. Twenty-six variables map naturally to an array var[26] indexed by c – ‘a’. The protocol: a lowercase letter pushes its variable’s value; = assigns the top of the stack …