c宏 # ##
#include <stdio.h>struct test {
intn0;
intn1;
char ch;
};
#define add_test_n(num) do { t.n##num ++; } while (0)
#define add_test(obj) do { t.obj ++; } while (0) /* 非注释 */
//#define add_test(obj) do { t.##obj ++; } while (0)/* 注释 */
int main()
{
struct test t = { 100, 100, 'a' };
add_test_n(1);// 在t.n后面连1 ->t.n1
add_test(ch); // 按非注释的,直接将obj替换成ch当然没问题;按注释的add_test(),是在t.后面连ch,也是t.ch,为什么报错?
printf("%d, %d, %c\n", t.n0, t.n1, t.ch);
return 0;
}
// 按非注释的,直接将obj替换成ch当然没问题;按注释的add_test(),是在t.后面连ch,也是t.ch,为什么报错?
http://stackoverflow.com/questions/13216423/error-pasting-and-red-does-not-give-a-valid-preprocessing-token 因为t.ch不是个合法的identifier。 本帖最后由 nswcfd 于 2016-09-13 19:06 编辑
It is often useful to merge two tokens into one while expanding macros.
This is called "token pasting" or "token concatenation".The `##'
preprocessing operator performs token pasting.When a macro is
expanded, the two tokens on either side of each `##' operator are
combined into a single token, which then replaces the `##' and the two
original tokens in the macro expansion.Usually both will be
identifiers, or one will be an identifier and the other a preprocessing
number.When pasted, they make a longer identifier.This isn't the
only valid case.It is also possible to concatenate two numbers (or a
number and a name, such as `1.5' and `e3') into a number.Also,
multi-character operators such as `+=' can be formed by token pasting.
However, two tokens that don't together form a valid token cannot be
pasted together.For example, you cannot concatenate `x' with `+' in
either order.If you try, the preprocessor issues a warning and emits
the two tokens.Whether it puts white space between the tokens is
undefined.It is common to find unnecessary uses of `##' in complex
macros.If you get this warning, it is likely that you can simply
remove the `##'.
----------------------------------------------
Preprocessing tokens fall into five broad classes: identifiers,
preprocessing numbers, string literals, punctuators, and other.An
"identifier" is the same as an identifier in C: any sequence of
letters, digits, or underscores, which begins with a letter or
underscore.Keywords of C have no significance to the preprocessor;
they are ordinary identifiers.You can define a macro whose name is a
keyword, for instance.The only identifier which can be considered a
preprocessing keyword is `defined'.*Note Defined::.
回复 3# nswcfd
:shock: 终于又出现了
页:
[1]