Skip to main content
\(\newcommand{\doubler}[1]{2#1} \newcommand{\binary}{\mathtt} \newcommand{\hex}{\mathtt} \newcommand{\octal}{\mathtt} \newcommand{\prog}{\mathtt} \newcommand{\lt}{<} \newcommand{\gt}{>} \newcommand{\amp}{&} \)

Section13.3Programming Exercises

The functions from Exercise 13.3.2 and Exercise 13.3.4 will be used for other exercises in subsequent chapters.

1

Enter the C program in Listing 13.2.1. Using the “-S” compiler option, compile it with differing levels of optimization, i.e., “-O1,” “-O2,” “-O3,” and discuss the assembly language that is generated. Compare the results with my solution in Listing 13.2.6. Is the optimized code easier or more difficult to read?

Solution
2

Write the function, writeStr, in assembly language. The function takes one argument, a char *, which is a pointer to a C-style text string. It displays the text string on the screen. It returns the number of characters displayed.

Demonstrate that your function works correctly by writing a main function that calls writeStr to display “Hello world” on the screen. Your main function can ignore the character count that is returned by writeStr.

Solution
3

Write the function, readLn, in assembly language. The function takes one argument, a char *, which is a pointer to a char array, for storing a text string. It reads characters from the keyboard and stores them in the array as a C-style text string. It does not store the ‘\n’ character. It returns the number of characters, excluding the NUL character, that were stored in the array.

Demonstrate that your function works correctly by writing a main function that prompts the user to enter a text string and then echoes the user's input, using the writeStr function from Exercise 13.3.2. When testing your program, be careful not to enter more characters than the allocated space. Explain what would occur if you did enter too many characters. Your main function can ignore the character count that is returned by writeStr and readLn.

Hint Solution
4

Modify the readLn function in Exercise 13.3.3 so that it takes a second argument, the maximum length of the text string, including the NUL character. Excess characters entered by the user are discarded.

Demonstrate that your function works correctly by writing a main function that prompts the user to enter a text string and then echoes the user's input, using the writeStr function from Exercise 13.3.2. When testing your program, be careful not to enter more characters than the allocated space. Your main function can ignore the character count that is returned by writeStr and readLn.

Hint 1 Hint 2 Solution
5

One problem with using writeLn in the solution to Exercise 13.3.4 is that it needs a newline after echoing the user's input string. Correct this problem. I do not recommend adding the newline character to the string before echoing it. See if you can solve the problem some other way.

Solution