# and # #的用法 in C language

Source: Internet
Author: User
Tags mul

I. GENERAL usage
we use # To change the macro argument to a string with # #把两个宏参数贴合在一起.
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
It is important to note that the macro parameter, where the macro definition is useful ' # ' or ' # # ', is no longer expanded.

1, non-' # ' and ' # # ' situations
#define TOW (2)
#define MUL (A, B) (a*b)

printf ("%d*%d=%d\n", TOW, TOW, MUL (Tow,tow));
This line of macros will be 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>
The 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 no longer being unfolded, but the solution to this problem is simple. Add an extra layer of intermediate conversion macros.
The intention of adding this layer is to expand all the macro parameters in this layer, then the macro (_STR) in the macro can get the correct macro parameters.

#define A (2)
#define _STR (s) #s
#define STR (s) _str (s)//Convert macro
#define _cons (A, b) int (a# #e # #b)
#define CONS (A, B) _cons (A, B)//CONVERT macro

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

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

Third, ' # ' and ' # # ' Some of the application exceptions
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);  That is: static int _anonymous70; 70 indicates the line number of the row;
First layer: ANONYMOUS (static int); --__ANONYMOUS0 (static int, __line__);
Second layer:--___ANONYMOUS1 (static int, _anonymous, 70);
Third layer:--static int _anonymous70;
That is, you can only unlock the current layer of macros, 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 string buffer size corresponding to a numeric type
#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];

"Alps_008":
Basically looked over, the landlord of the situation belongs to the general use:

"#把宏参数变为一个字符串, use # #把两个宏参数贴合在一起"



#include <stdio.h>
#include <string.h>
#define STRCPY (A, B) STRCPY (a# #_p, #b)//Add the character _p behind the first argument and turn the second argument into a string

int main ()
{
Char var1_p[20];
Char var2_p[30];
strcpy (var1_p, "AAAA");
strcpy (var2_p, "bbbb");
STRCPY (VAR1,VAR2); equals strcpy (Var1_p, "var2");
STRCPY (VAR2,VAR1); equals strcpy (Var2_p, "var1");
printf ("%s\n", var1_p);
printf ("%s\n", var2_p);
return 0;
}

"Jeffer007":
Token-pasting Operator (# #)


Preprocessor_token_pasting.cpp
#include <stdio.h>
#define Paster (N) printf_s ("token" #n "=%d", token# #n)
int token9 = 9;

int main ()
{
Paster (9);
}

Output
TOKEN9 = 9

Stringizing Operator (#)
Stringizer.cpp
#include <stdio.h>
#define Stringer (x) printf (#x "\ n")
int main () {
Stringer (in quotes with the printf function call);
Stringer ("in quotes when printed to the screen");
Stringer ("this: \" Prints an escaped double quote ");
}

Output
In quotes in the printf function call
"In quotes when printed to the screen"
"This: \" Prints an escaped double quote "

5 First look at the following three statements:

#define Conn(x,y) x##y#define ToChar(x) #@x#define ToString(x) #x
    • 1
    • 2
    • 3
(1). # # Connection operator

# #表示连接 (token pasting, or token concatenation,merge, tokens to one while expanding macros). x##yWhat does it say? Represents x connection Y, for example:

int n = Conn(123,456);     ==> int n=123456;char* str = Conn("asdf", "adf"); ==> char* str = "asdfadf";
    • 1
    • 2
    • 3
    • 4

How, it's amazing!

Note that the # #的左右符号必须能够组成一个有意义的符号, otherwise the preprocessor will error.

(2). #@ character operator

#@xCan only be used in macro definitions with passed-in parameters, and must be placed before parameter names in the macro definition body. The function is to convert the single character parameter names into characters, in a pair of single references in fact, is to give the X plus one quotation mark, the result is a return const char .
For example,

char a = ToChar(1);     ==> char a=‘1‘;
    • 1
    • 2

Do a cross-border test.

char a = ToChar(123);     ==> char a=‘3‘;
    • 1
    • 2

But if your parameter exceeds four characters, the compiler will give you an error! error C2015: too many characters in constant: P

(3). # string operator

#表示字符串化操作符 (stringification). It does this by converting the name of the incoming parameter in the macro definition to the parameter name string enclosed in a pair of double quotation marks. It can only be used in macro definitions with incoming parameters, and must be placed before the parameter names in the macro definition body. To put it bluntly, he was giving X double quotes:

char* str = ToString(123132);     ==> char* str="123132";
    • 1
    • 2

If you want to string the expanded macro parameters, you need to use a two-layer macro.

#define xstr(s) str(s)#define str(s) #s#define foo 4str (foo)     ==> "foo"xstr (foo)     ==> xstr (4)     ==> str (4) ==> "4"
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

The s parameter is string in the STR macro, so it is not prioritized for macro expansion. The s parameter, however, is a common parameter of the XSTR macro that has been expanded by the macro before being passed to the STR macro.

(4). \ line Continue operation

\ line continue operation when a defined macro cannot be complete with one line, you can use "\" (backslash) to indicate the next line to continue the definition of the macro.

Note: Do not add line breaks to the last line.

The pre-processor of the VC will automatically remove the \ and newline returns before compiling (write multiple lines, there can be no space after the backslash, otherwise the compiler (arm or VC) will error! ), so as not to affect reading, without affecting the logic, happy.

(5). __va_args__

The __VA_ARGS__ macro is used to accept an indefinite number of arguments. For example:

#define eprintf(...) fprintf (stderr, __VA_ARGS__)eprintf ("%s:%d: ", input_file, lineno)    ==>  fprintf (stderr, "%s:%d: ", input_file, lineno)
    • 1
    • 2
    • 3
    • 4
    • 5

You can omit the parameter input when the __VA_ARGS__ macro front # #时. For example:

#define eprintf(format, ...) fprintf (stderr, format, ##__VA_ARGS__)eprintf ("success!\n")    ==> fprintf(stderr, "success!\n");

# and # #的用法 in C language

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.