C Primer Plus (16)

Source: Internet
Author: User

16.1 step 1 of the translation procedure

Before preprocessing a program, the compiler will translate it several times.
The compiler first maps the characters in the source code to the source character set.
Second, the compiler searches for instances followed by the backslash and deletes them. That is, two physical rows
Printf ("That's wond \
Erful! \ N ");
Convert to a logical line: printf ("That's wonderful! \ N ");
Next, the compiler divides the text into a pre-processed linguistic symbol sequence, a blank character sequence, and a comment sequence. The compiler replaces each comment with a space character.
Finally, the program enters the preprocessing stage. The pre-processor looks for possible pre-processing settings.
These commands start with a line and are identified by the # symbol.

16.2 obvious constant: # define

The # symbol is used as the beginning of the row for preprocessing.
Commands can appear anywhere in the source file. The scope of the instruction definition starts from the position where the definition appears until the end of the file.
Each # define row consists of three parts.
The first part is the instruction # define itself.
The second part is selected abbreviations, which are called macros. As in this example, these macros are used to represent values. They are called Class Object macros. The macro name cannot contain spaces and must follow the naming rules of C variables.
The third part is the replacement list or subject.
When a macro instance is found in a program, the Preprocessor always uses an entity to replace the macro. The process from macro to final replacement of text becomes macro.

When using # define, multiple physical rows can be used. A backslash is added at the end of a line to extend the line to the next line. Note that the second line must be left aligned, no. spaces at the beginning are also part of the subject.
Generally, after the Preprocessor discovers a macro in the program, it replaces the macro with its equivalent replacement text. If the string contains red, it will continue to be replaced.
The exception is that the macro printf ("TWO: OW") in double quotation marks will output TWO: OW instead of the subject.

16.2.1 language symbols

Technically, the system regards the macro subject as a string of the language symbol type, rather than a string of the character type.
# Define FOUR 2*2 has a language symbol: 2*2.
# Define SIX 2*3 has three language symbols: 2, *, and 3. When the subject is interpreted as a character string, the Preprocessor replaces SIX with 2*3, that is, additional spaces are also used as part of the replacement text. However, when the subject is interpreted as a language symbol, the preprocessing replaces SIX with three language symbols separated by a single space, that is, 2*3.

The C compiler processes language symbols in a more complex way than the pre-processor.

16.2.2 redefinition of constants

Suppose you define LIMIT as 20, and then define LIMIT as 25 in this file. This process is called a redefinition constant.

The following two definitions are the same:
# Define SIX 2*3
# Define SIX 2*3
The two have three identical language symbols, and the extra spaces are not part of the subject. The following definitions are considered different:
# Define SIX 2*3
The preceding formula has only one language symbol, so it is different from the previous two definitions.
You can use the # undef command to redefine the macro.

16.3 use parameters in # define

By using parameters, you can create class function macros with similar shapes and functions. Macro parameters are enclosed in parentheses.
For example, # define SQUARE (X) X * X
In the program, you can use z = SQUARE (2 );
An example program:

# Include <stdio. h>
# Define SQUARE (X) X * X
# Define PR (X) printf ("The result is % d. \ n", X)
Int main (void)
{
Int x = 4;
Int z;
Printf ("x = % d \ n", x );
Z = SQUARE (x );
PR (z );
PR (SQUARE (x + 2 ));
PR (100/SQUARE (2 ));
Printf ("x = % d \ n", x );
PR (SQUARE (++ x ));
Return 0;
}

This is different from what we expect, because the pre-processor does not perform computation but only replaces strings. When x appears early, the pre-processor replaces x + 2 with the string. Therefore, x * x is changed to x + 2 * x + 2.
To change the result, you only need to add a few parentheses, for example, # define SQUARE (X) * (X)

16.3.1 create a string using macro parameters: # Operator

Macros in strings in quotation marks are treated as plain text rather than as a replaceable language symbol.
If you really want to include macro parameters in the string, you can use #. If x is a macro parameter, # x can convert the parameter name to a corresponding string. This process is called string.

# Define PR (X) printf ("The square of" # X "is % d. \ n", (X) * (X ))
Int y = 5; PR (y );
It is replaced with printf ("The square of" "y" "is % d. \ n", (y) * (y ));
Then, the string connection function converts the three adjacent strings into one:
Output The square of y is 25.

16.3.2 pre-processor adhesive: # Operator

Like the # operator, the # operator can be used to replace class function macros. ### Can also be used to replace Class Object macros. This operator combines two language symbols into a single language symbol.
For example, # define XNAME (n) x # n
The macro call of XNAME (4) is displayed in the following form: x4

16.3.3 variable macros:... and _ VA_ARGS __

The idea of implementation is (that is, three periods ). In this way, the predefine _ VA_ARGS _ can be used in the replacement part to indicate what the ellipsis represents.
For example, # define PR (...) printf (_ VA_ARGS __)
PR ("Hello"); Expand the parameter "Hello ";
# Define PR (X,...) printf ("Message" # X ":" _ VA_ARGS __)
Double x = 48; PR (1, "x = % g \ n", x );
Output Message 1: x = 48

16.4 macro or function

The choice between macros and functions is actually a trade-off between time and space.
Macros generate Inline code, that is, statements in the program. If a macro is used for 20 times, 20 lines of code are inserted. If the function is used for 20 times, only one copy of the function statement is saved in the program.
However, the transfer from function design to program control takes more time.
One advantage of a macro is that it does not check the variable type, but it will produce a strange phenomenon if you do not pay attention to it.

16.5 File Inclusion: # include

After the pre-processor discovers the # include command, it will find the file name followed by it and include the content of this file into the current file, you can just type all the content in the contained file to the specific location of the source file.
Traditionally, the suffix. h is used to indicate the header file, which contains information placed in the program header.
Containing large header files does not necessarily increase the program size significantly. In many cases, the content in the header file is the information required by the compiler to generate the final code, rather than the specific statement added to the final code.
Browsing any standard header file will give you a clear concept of the type of information in the object.
In addition, many use header files to declare external variables shared by multiple files.

16.6 other commands

16.6.1 # undef command

# The undef command cancels the definition of a given # define. It can be canceled even if it is not defined.
For example, # define LIMIT 400 # undef LIMIT

16.6.2 defined: views of the C Preprocessor

If the identifier in C is the macro name created by the # define Command signed by the file, and the # undef command is not used to disable the identifier, the identifier is defined.
If the identifier is not a macro but a C variable with a file scope, the Preprocessor treats the identifier as undefined. For example, int q; // q is not defined

16.6.3 Conditional compilation

I. # ifdef, # else, And # endif commands

# Ifdef MAVIS
Statement1;
# Else
Statement2;
# Endif
If the pre-processing defines the identifier MAVIS, execute statement1; otherwise, execute statement2.

Ii. # ifndef command

# Ifdef command.
# Ifndef SIZE
# Define SIZE 100
# Endif

Iii. # if and # elif commands

# The if command is more like if in General C; # if followed by a constant integer expression.
Many new methods improve another method to determine whether a name has been defined.
No # ifdef VAX
Instead, use # if defined (VAX)

16.7 inline functions

It takes some time to call a function. One reason for using class function macros is to reduce execution time.
C99 also provides an inline function.
To create an inline function, use the inline operator in the function declaration.
For example, inline void eatline ()
Inline functions should be short. For a long function, calling a function takes less time than executing the function body. In this case, using inline functions does not save much time.
The Inline Function Definition and the call to the function must be in the same file.
C only allows a unique definition of a function, but this restriction is relaxed for inline functions.
C allows mixed use of inline function definitions and external function definitions.

16.8 C library

16.8.1 access the C library

1. Automatic access

In many systems, you only need to compile the program and some common library functions are automatically available.
Remember, you should declare the type of the function used, usually including the appropriate header file.

Ii. File Inclusion

If a function is defined as a macro, you can use the # include command to include the file that owns the definition.

Iii. Library inclusion

The library option tells the system where to find the function code

16.9 general tool Library

16.9.1 exit () and atexit ()

The atexit () function uses the function pointer as the parameter. The type of the function registered by atexit () should be a void function that does not accept any parameters.
When calling the exit () function, execute these functions in the first and later order.
Exit () will do some self-cleaning work, refresh all output streams, and close the open stream.

16.10 diagnostic Database

The diagnostic library supported by the header file assert. h is a small library designed to assist debugging programs.
It consists of a macro assert (), which accepts an integer expression as a parameter. If it is false, write an error message to the standard error stream and call the abort () function to terminate the program.
For example, assert (z> = 2)
You can use # define NEDBUG to disable all the assert () statements in the file.

16.11 memcpy () and memmove () in string. h ()

The two functions are prototype:
Void * memcoy (void * restrict s1, const void * restrict s2, size_t n );
Void * memmove (void * s1, const void * s2, size_t n );
Both functions copy n bytes of data from s2 to s1, and return the value of s1.
The difference between the two is that the first function does not allow overlapping areas.
The third parameter can be num * sizeof (int)

Related Article

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.