newline character "\" macro definition \ string multiple line writing

Source: Internet
Author: User
Tags function definition mul


When there is too much code in your code, it is especially inconvenient to read the code, and you need to use a newline character "\". Be aware of two points when using line breaks:

The 1.c compiler is based on ";" To determine if it is a statement, so as long as it's not wrapped in parentheses, it's OK.

2. Do not put the space in the middle.


line wrap problem when string constants are definedIf we place a backslash at the end of a line of code, the C language compiler ignores line breaks at the end of lines, and the contents of the next line are counted as the bank's content. Here the backslash plays a role in the continuation of the line.
Building a longer string is a common use for continuation, and a function is to define a macro that spans rows.
If we don't use backslashes, when we try to initialize a string that spans multiple lines, the C language compiler emits a warning. As shown in the following statement:
Char letters[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ
Abcdefghijklmnopqrstuvwxyz "};
But we use backslashes at the end of the line, so we can write string constants across lines, as follows:
Char letters[] = {"Abcdefghijklmnopqrstuvwxyz\
Abcdefghijklmnopqrstuvwxyz "}; You can avoid adding more spaces to the entire string by entering a string from the beginning of the continuation line. To sum up, the above statement defines a character array letters,
and initialize it to the following initial value: "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"

The C language also has a method of splitting a string, which is to write multiple adjacent strings. These strings are separated by 0 or more blanks, modifiers, and line breaks. The C language compiler will automatically concatenate these strings. Therefore, the following expression: "One" "Two" "three" is actually equivalent to "Onetwothree". Therefore, the initialization statements for the preceding rows can also be completed in the following form:
Char letters[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"} below gives an example, the following three printf statements actually accept only the parameters, printf ("programing in C-fun\n"); Programing in C was fun printf ("Programming in C" "is fun\n"); Programing in C was fun printf ("Programming" "in C" "is fun" \ n);//programing in C is fun///////////////////////////// Macro definition hasno parameter macro definitionAndwith parameter macro definitionTwo kinds.
The general form of a macro definition without parameters is
                      # define identifier character sequence
The identifier after # define is called the macro definition name (the macro name) and requires a spaces separation between the macro name and the sequence of characters. This macro definition requires the compiler to compile the preprocessor to replace all subsequent naming occurrences in the source program (except in the case of a string constant) with a sequence of characters. The most commonly used definition of symbolic constants is the simplest application of a macro definition. If any:
# define TRUE 1
# define FALSE 0
In the source program file where they are defined, the word true will be replaced with 1, and the word false will be replaced with 0.
There can be several spaces, tabs, but no other characters before the # defined by the macro. The macro definition is a separate line in the source program,line breaks are the end flags for macro definitions。 If a macro definition is too long and one row is not enough,a continuation method may be used. The continuation line is to type the symbol "" before the key person carriage return character. Note Carriage return must be followed by the symbol "", and no other symbols can be inserted in the middle. 、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、 、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、 、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、A macro definition description macro defines ano parameter macro definitionAndwith parameter macro definitionTwo kinds.
The general form of a macro definition without parameters is
                      # define identifier character sequence
The identifier after # define is called the macro definition name (the macro name) and requires a spaces separation between the macro name and the sequence of characters. This macro definition requires the compiler to compile the preprocessor to replace all subsequent naming occurrences in the source program (except in the case of a string constant) with a sequence of characters. The most commonly used definition of symbolic constants is the simplest application of a macro definition. If any:
# define TRUE 1
# define FALSE 0
In the source program file where they are defined, the word true will be replaced with 1, and the word false will be replaced with 0.
There can be several spaces, tabs, but no other characters before the # defined by the macro. The macro definition is a separate line in the source program, and the newline character is the end mark of the macro definition. If a macro definition is too long and one row is not enough,a continuation method may be used. The continuation line is to type the symbol "" before the key person carriage return character. Note Carriage return must be followed by the symbol "", and no other symbols can be inserted in the middle.
The valid scope of a macro definition is called the scope of the macro definition name,The scope begins at the end of the definition of the macro to the source program file where it resides. The scope of the macro definition name is not affected by the Sub program structure. You can use the preprocessing command to #undef terminate the scope of the macro definition name.
In the new macro definition, you can use the previously defined macro name. For example
# define R 2.5
# define PI 3.1415926
# define Circle 2*pi*r
# define Area pi* R * r
The circle in the program is expanded to 2*3.1415926* 2.5, and area is expanded to 3.1415926*2.5*2.5.
If necessary, the macro name can be defined repeatedly. After being repeatedly defined, the original meaning of the macro name is replaced by the new meaning.

     Typically, macro definitions with no parameters are used to define constants. In the program unification uses the macro name to represent the constant value, facilitates the procedure to unify, is not easy to make mistakes, also facilitates the modification, can improve the program readability and the portability. In particular, a macro definition of the number of array elements, and the macro name to define the number of elements of the array can partially compensate for the lack of fixed number of elements.
      Note: the preprocessor, when working with macro definitions, , works only for the replacement of character sequences without any grammatical checking. If the macro is not defined properly, the error will not be discovered until the compile phase after preprocessing. A macro definition ends with a newline, and does not require symbols such as semicolons to be delimiters. If the following definition is defined:
   # define PI 3.1415926
The statement that the circumference of the circle was expected to be pi,
   c=2*pi*r;
Chinghong expands to
    C=2*3.1415926*r;
This will not meet the desired requirements.
   with a parameter macro defines the ability to further expand the definition of a parameterless macro, replacing the character sequence with a parameter replacement. The general form with a parameter definition is
    # define identifier (parameter table) character sequence
The parameters in the parameter table are separated by commas, and the sequence of characters should contain the parameters in the parameter table.
when you define a macro with parameters, the macro name identifier and the left parenthesis are not allowed to have whitespace characters, which should be immediately followed, otherwise it becomes a macro definition with no parameters. If there is a macro definition:
   # define MAX (A,b) ((A) > (B)? ( A):(B))

The Code y= MAX (P+q, u+v) will be replaced with y= (P+Q) > (u+v)? ( P+Q):(u+v).
The macro invocation in the            program is replaced by this, using the sequence of the actual parameter numbers in the macro invocation (such as P+q and U+v) Replaces all occurrences of a formal argument in a sequence of characters (such as substituting p+q for all formal argument a, substituting u+v for all formal argument b), and other characters in the macro-defined character sequence that are not formal arguments are retained. The sequence of characters that is formed, that is, the expansion substitution result for a macro call. The macro invocation must provide the same number of arguments as the formal parameter in the macro definition.
       Note: The difference between a macro call and a function call. function calls are implemented when the program is running, the macro expansion is done during the preprocessing phase of the compilation, the function call occupies the program run time, the macro call takes up only the compile time, and the function call has a type requirement for the argument, while the macro calls the actual parameter and the macro-defined formal parameter has no type concept, only the correspondence of the sequence A function call can return a value, and the macro call gets the desired C code. In addition, when a function is called, the argument expression is evaluated independently of the previous, and the function body is executed. A macro call is a sequence of argument numbers that replaces formal arguments. After the substitution, the real parameter character sequence is connected with the adjacent characters naturally, and the independence of the actual parameters is not necessarily still. As the following macro definition:
   # define SQR (x) x*x
wants to implement the square calculation of an expression. For macro call
   p=sqr (y)
to get the desired macro expand p= y*y. However, macro expansion for macro invoke Q=SQR (U+V) is q=u+v*u+v. Obviously, the latter's unfolding results are not what programmers want. To maintain the independence of the actual parameter substitution, you should enclose the formal argument in the macro definition. Further, in order to guarantee the independence of the macro invocation, the macro definition of the formula should also include the
number. If the SQR macro definition is rewritten:
   # define SQR ((x) * (x))
is the correct macro definition.

For the short expression calculation function, or in order to improve the execution efficiency of the program, avoid the function call of the allocation of storage units, the preservation of the site, parameter value transfer, release memory unit and so on. You can rewrite a function definition as a macro definition. So you can make your program more concise by using macro definitions rationally.


use some macros to track debugging

The a N S I standard describes five predefined macro names. They are:

_ L I N E _ (two underscores), corresponding%d

_ F I L E _ corresponds to%s

_ D A T E _ corresponds to%s

_ T I M E _ corresponds to%s

_ S T D C _

If the compilation is not standard, it may support only a few of the macro names above, or it is not supported at all. Remember to compile the program

Other predefined macro names may also be provided.

_ L i n e _ and _ F I L e _ macros are discussed in the section about # L i n E, where the remaining macro names are discussed.

_ D at E _ macro instruction contains a string of month/day/year, indicating the date when the source file was translated to code.

The time of source code translation into the target code is contained in _ T I M E _. String form last: minutes: seconds.

If the implementation is standard, then the macro _ S T D C _ contains a decimal constant of 1. If it contains any other number, the implementation is

Non-standard.

You can define macros, such as:

When _DEBUG is defined, the output data information is in line with the file

#ifdef _DEBUG

#define DEBUGMSG (msg,date) printf (msg);p rintf ("%d%d%s", Date,_line_,_file_)

#else

#define DEBUGMSG (Msg,date)

#endif

20, macro definition to prevent use is an error

included with parentheses.

Example: #define ADD (A,B) (a+b)

Use Do{}while (0) statement to contain multiple statements to prevent errors

For example: #difne do (a,b) a+b;\

a++;

When applied: if (...)

Do (A,B); Generate an error

Else

Workaround: #difne Do (a,b) do{a+b;\

a++;} while (0)


Usage of "#" and "# #" in macros
I. GENERAL usage
We use # To change the macro parameter to a string, with the # #把两个宏参数贴合在一起 (which is said to be the operation on the source file in preprocessing).
Usage:
#include <cstdio>
#include <climits>
using namespace Std;

#define STR (s) #s
#define CONS (a,b) int (a# #e # #b)

int main ()
{
printf (STR (VCK)); Output string "Vck"
printf ("%d\n", CONS (2,3)); 2E3 Output: 2000
return 0;
}

Second, when the macro parameter is another macro
The local macro parameter that needs to be noted for "#" or ' # # ' in the macro definition is not expanded.

1, not ' ' # ' and ' # # ' situation
#define TOW (2)
#define MUL (A,b) (a*b)

printf ("%d*%d=%d\n", TOW, TOW, MUL (Tow,tow));
This line of macros is expanded to:
printf ("%d*%d=%d\n", (2), (2), ((2) * (2)));
The parameter tow in the MUL will be expanded to (2).

2, when there is ' # ' or ' # # '
#define A (2)
#define STR (s) #s
#define CONS (a,b) int (a# #e # #b)

printf ("int max:%s\n", STR (Int_max)); Int_max #include <climits>
This guild is expanded to:
printf ("int max:%s\n", "Int_max");

printf ("%s\n", CONS (A, a)); Compile error
This line is:
printf ("%s\n", int (AeA));

Int_max and A are not going to be expanded, but the solution to this problem is simple. Add one more layer of intermediate conversion macros.
The idea of adding this macro is to expand all of the macro parameters in the middle tier , and then the macro in the conversion macro (_STR) can get the correct macro parameters.

#define A (2)
#define _STR (s) #s
#define STR (s) _str (s)//Convert macros
#define _CONS (a,b) int (a# #e # #b)
#define CONS (a,b) _cons (a,b)//Convert macros

printf ("int max:%s\n", STR (Int_max)); The maximum value of the Int_max,int type for a variable #include <climits>
Output is: int max:0x7fffffff
STR (Int_max)--> _str (0x7fffffff) is then converted to a string;

printf ("%d\n", CONS (A, a));
Output as: 200
CONS (A, a)--> _cons ((2), (2))--> Int ((2) E (2))

Third, the ' # ' and ' # # ' application of some special cases
1. merging anonymous variable names
#define ___ANONYMOUS1 (Type, var, line) type var# #line
#define __ANONYMOUS0 (type, line) ___anonymous1 (type, _anonymous, line)
#define ANONYMOUS (Type) __anonymous0 (type, __line__)
Example: ANONYMOUS (static int); namely: static int _anonymous70; 70 indicates the line number;
First layer: ANONYMOUS (static int); --> __anonymous0 (static int, __line__);
Second layer:--> ___anonymous1 (static int, _anonymous, 70);
Third layer:--> static int _anonymous70;
That is, each time only the current layer of the macro can be solved, so __line__ in the second layer can be untied;

2. Filling Structure
#define FILL (a) {A, #a}

Enum Idd{open, close};
typedef struct msg{
IDD ID;
const char * MSG;
}msg;

MSG _msg[] = {Fill (OPEN), fill (close)};
Equivalent:
MSG _msg[] = {{Open, ' open '},
{Close, ' close '}};

3. Record file name
#define _GET_FILE_NAME (f) #f
#define GET_FILE_NAME (f) _get_file_name (f)
static char file_name[] = Get_file_name (__file__);

4, get a numeric type corresponding to the string buffer size
#define _TYPE_BUF_SIZE (TYPE) sizeof #type
#define TYPE_BUF_SIZE (Type) _type_buf_size (type)
Char buf[type_buf_size (INT_MAX)];
--> Char buf[_type_buf_size (0x7fffffff)];
--> Char buf[sizeof "0x7fffffff"];
This is equivalent to:
Char buf[11];

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.