首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

宏定义的macro究竟支持空格不

2013-09-06 
宏定义的macro到底支持空格不?#define MEAN(x, y) (x + y) / 2//compiled in code::blockint main (void){

宏定义的macro到底支持空格不?

#define MEAN(x, y) (x + y) / 2  //compiled in code::block
int main (void)
{
printf ("%d\n", MEAN (1, 3));  //print: 2
return 0;
}

书上说宏名字中不允许有空格,但上面这段程序没有任何错误。
是说函数宏支持空格,但对象宏不支持?
[解决办法]
#define identifier token-sequence

不带参数的宏,identifier前后的空格都会被丢弃。
#define identifier( identifier-list ) token-sequence

带参数的宏,第一个identifier和'('之间不能有空格,不然就会被解释成第一种。
[解决办法]
引用:
Quote: 引用:

#define identifier token-sequence

不带参数的宏,identifier前后的空格都会被丢弃。
#define identifier( identifier-list ) token-sequence

带参数的宏,第一个identifier和'('之间不能有空格,不然就会被解释成第一种。

你这个倒是一针见血。
可否再追问下,函数宏对括号处理的过程是怎么样的?
另外,有没有直观的办法看到宏展开后的c代码?还是只能像目前这样推测?


<<The C Programming Language>> 2nd Edition
When a macro has been defined in the second form(with parameters), subsequent textual instances of the macro identifier followed by optional white space, and then by (, a sequence of tokens separated by commas, and a ) constitute a call of the macro.

standard C 98/99
不带参数的宏是object-like macro,带参数的是function-like macro
宏定义里跟在宏名后面的lparen(左括号)是一个预处理token,引出后面的替换列表,右括号用来结束替换列表,中间插入的成对括号会被忽略。

引用





[解决办法]
。。按错了,接着上面。
引用一下原文,以防因为英语水平差误导楼主。。。

A preprocessing directive of the form

# define identifier lparen identifier-list_opt ) replacement-list new-line
# define identifier lparen ... ) replacement new-line


# define identifier lparen identifier-list , ... ) replacement-list new-line


defines a function-like macro with arguments, similar syntactically to a function call. The parameters are specified by the optional list of identifiers, whose scope extends from their  declaration in the identifier list until the new-line character that terminates the #define preprocessing directive. Each subsequent instance of the function-like macro name followed by a ( as the next preprocessing token introduces the sequence of preprocessing tokens that is replaced by the replacement list in the definition (an invocation of the macro). The replaced sequence of preprocessing tokens is terminated by the matching ) preprocessing tokens. Within the sequence of preprocessing tokens making up an invocation of a function-like macro, new-line is considered a normal white-space character.


ps:抄错或者打错字本人概不负责。。

[解决办法]
引用:
Quote: 引用:

#define identifier token-sequence

不带参数的宏,identifier前后的空格都会被丢弃。
#define identifier( identifier-list ) token-sequence

带参数的宏,第一个identifier和'('之间不能有空格,不然就会被解释成第一种。

你这个倒是一针见血。
可否再追问下,函数宏对括号处理的过程是怎么样的?
另外,有没有直观的办法看到宏展开后的c代码?还是只能像目前这样推测?


不能说是推测吧。。虽然我也不知道怎么能看到,但是根据标准来写没错的,多测试几下就明白了。。

热点排行