"C and the Hands" chapter 14th practice

Source: Internet
Author: User

Chapter Questions

1. The preprocessor defines 5 symbols, gives the file name to compile, the current line number of the line, the current date and time, and whether the compiler is an ANSI C compiler. Cite one possible use for each symbol.

Answer: When printing error messages, file names and line numbers can be useful, especially in the early stages of debugging. In fact, assert macros use them to implement their own functionality. _data_ and _time_ can compile the version information into the program. Finally, _STDC_ can be used in conditional compilation to select the structure of ANSI C and pre-ANSI in source code that must be compiled by two types of compilers.

2. Say two advantages of replacing literal constants with names defined by # define.

Answer:first,a well chosen name gives the reader some idea of the meaning of a quantity,whereas a literal constant conveys Only it Value,second,literal constants that is used more than once is easier to change if they is defined in a single Place.

(First, a proper name can give the reader more information about the quantity, whereas a literal constant conveys only its value, and secondly, a literal constant defined in one place is easier to change when multiple occurrences occur)

3. Write a macro for debugging and print out any expression. It should accept two parameters when it is called. The first one is the printf format code, and the second is the expression that needs to be printed.

Answer

#define PRINT(format, value) \    printf (""format"\ n" ,           __file__, __line__, #value, value);
// Invocation Mode Debug_print ("%d"3); // Output  - 3 =4

4. What will the following program print out? You must be very careful when you expand the # define content!

#defineMAX (a) (a) > (b)? (a):(B)#defineSQUARE (x) x*x#defineDOUBLE (x) x+xMain () {intx, Y, Z Y=2, z =3; X=MAX (y,z); printf ("%d%d%d\n", x, Y, z); Y=2, z =3; X= MAX (++y, + +z); printf ("%d%d%d\n", x, Y, z); X=2; Y=SQUARE (x); Z= SQUARE (x+6); printf ("%d%d%d\n", x, Y, z); X=2; Y=3; Z= MAX (5*double (x), + +y); printf ("%d%d%d\n", x, Y, z);}

Answer

3 2 3

5 3 5

2 4 20

2 4 12

The 5.putchar function is defined in file stdio.h, although its content is longer, but it is implemented as a macro, why do you think it is defined in this way?

Answer:because Putchar is invoked (called) so often,speed of invocation was considered of primary importance,implementing it as A macro eliminates the overhead of a function call.

(Because the Puchar is called more often, the speed of the call is an important factor to consider, the execution of the macro is less expensive than the function requires)

6. Is the following code wrong? If so, where is wrong?

Answer: We cannot judge by the given source code judgment. If the process is implemented as a macro and its parameters are evaluated more than once, increasing the side effects of the subscript value may result in incorrect results.

7. Is the following code wrong? If so, where is wrong?

Answer: There are several areas of error in this code, several of which are more subtle. The main problem is that the macro has parameters that depend on side effects (increasing the subscript value), which is very dangerous, and that the name of macro does not prompt the actual task it performs (this is the second problem), which is further increased, assuming that the loop is later changed to:

The program will fail at this point, although it looks the same. The last problem is that macro always accesses the two elements in the array, so if size is an odd value, the program will fail.

(Why does the program fail if the code changes to the above code?) Isn't there no more side effects? First, let's look at the function of this program "sum all the value in the array", meaning that the sum of all the values of the array is calculated, the source code means to add two consecutive array values each time, that is, sum (value) means to calculate array[i] + Array[i+1] value, so say "dependent" macro side effects, it is deliberately using the side effects of the macro implementation, the code after the change, you can remove the macro directly computed array value)

8. Is the following code wrong? If so, where is wrong?

In the file Header1.h

In the file header2.h

Answer

Answer:nothing is Wrong,they all include the Other,and it first appears that the compiler would read them alternately Unti L It include nesting limit is reached. In fact this does isn't happen because of the conditional compilation Directives,whichever file is included first defines it s own symbol and then causes the other to being included,when it tries to include the first one again,the entire file is skip Ped.

(There is no mistake, they include each other, and it first appears that the compiler will alternately read them to know that the nesting reaches the limit, in fact this does not happen because the conditional compilation directives, any one file in the first definition of the creation of a glyph, so that the other files will be included in the skip it)

9. In an attempt to improve the readability of the program, a programmer wrote the following statement.

Is this code wrong? If so, where is wrong?

Answer

UNFORTUNATELY,SIZEOF is evaluated (evaluation) after the preprocessor (pre-processor) has finished its work,which means that this won ' t work, An alternate approach would is the use of the values defined in the limits.h include file.

(Unfortunately, the evaluation of sizeof is after the preprocessor has finished working, which means that the program will not work, and a substitute method is to use the limits header file to determine the value)

where sizeof (int) = = 2 The expression is to determine whether the value of int is two bytes, the size of the type is defined in the header file of limits, the int value is between int_min to Int_max, So you can use the value defined in Limits.h instead of the sizeof statement.

This chapter exercises

1. Your company has placed a program in the market to process financial transactions and print out their reports. In order to expand the potential market, the program is sold in several different versions, each with a combination of different options-the more options, the higher the price, and your task is to implement the code for a print function, so it can be easily compiled, producing different versions of the program. Your function name is Print_ledger. It takes an int parameter, no return value, and it should call one or more of the following functions, depending on which symbol, if any, is defined when the function is compiled.

Each function accepts a single int parameter, passing the value you receive to the function you are calling.

Answer

void print_ledger (int  arg) {    #if option_long        Print_ledger_long (arg );     #elif option_detailed        print_ledger_detailed (ARG);     #else         Print_ledger_default (ARG);     #endif }

If you write the above code like I do, then, you are the same as I do not understand the topic, because two options are likely to be selected, the possibility that the #elif instructions can not be used, let us see the correct answer

void print_ledger (int  arg) {#ifdef option_long    #define OK 1    Print_ Ledger_long (ARG); #endif     #ifdef option_detailed    #define OK 1    print_ledger_detailed (ARG); #endif     #ifndef OK    print_ledger_default (ARG); #endif }

2. Write a function that returns a value that indicates the type of computer on which the function is run. This function will be used by a program that can run with many different computers.

We will use conditional compilation to implement this magic, your function should be called cpu_type, it does not accept any parameters, when your function is compiled, in the table below the "defined" column of one of the symbols may be defined, your function should return the corresponding symbol from the "Return value" column, If all the symbols in the left column are undefined, then the function returns the value Cpu_unknown, and if more than one symbol is defined, the result is undefined.

The symbol in the return value column is defined by a # define as a variety of different shaping values, whose contents are in the header file cpu_type.h.

Answer

#include <stdio.h>#include"cpu_type.h"intCPU_type (void){#ifDefined (VAX)returnCpu_vax;#elifDefined (M68000)returncpu_68000;#elifDefined (M68020)returncpu_68020;#elifDefined (I80386)returncpu_80386;#elifDefined (X6809)returncpu_6809;#elifDefined (X6502)returncpu_6502;#elifDefined (U3B2)returncpu_3b2;#else    returnCpu_unknown;#endif}

"C and the Hands" chapter 14th practice

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.