类似函数的宏的错误扩展 [英] Incorrect expansion of a function-like macro
问题描述
晚上好,
我对宏有问题.我应该拿出一个宏ENTRY
,它将一个值放入数组(给出了scanf("%d",&ENTRY(x,i))
).
Good evening,
I have a problem with macros. I am supposed to come up with a macro ENTRY
, that puts a value into an array ( scanf("%d",&ENTRY(x,i))
was given).
我尝试过:#define ENTRY (a,b) (a[b-1])
,但这没用.
它创建了一个编译器错误,指出未声明a和b.
但是我认为我不必声明在宏中使用的变量,尤其是因为,例如:#define min (a,b) ((a)<(b)?(a):(b))
在另一个程序中工作过.
I tried: #define ENTRY (a,b) (a[b-1])
, but that didn't work.
It created a compiler error that says, that a and b are undeclared.
But I thought that I don't have to declare variables used in macros, especially because, for example: #define min (a,b) ((a)<(b)?(a):(b))
worked in another program.
那我在做什么错了?
#include <stdio.h>
#define N 3
#define ENTRY (a,b) (a[b-1])
int main(void)
{
int x[N],i;
float y[N];
for(i=1;i<=N;i++){ printf("x_%d = ",i);scanf("%d",&ENTRY(x,i));}
for(i=1;i<=N;i++){ printf("y_%d = ",i);scanf("%lf",&ENTRY(y,i));}
return 0
}
推荐答案
Function-like macro definitions can't have whitespace after the macro name
#define ENTRY (a,b) (a[b-1]) // wrong
=>
#define ENTRY(a,b) ((a)[(b)-1]) // correct
...
...
控制线:
...
control-line:
...
# define
标识符 lparen 标识符列表选择 )
替换列表换行
# define
标识符 lparen ... )
替换列表 换行符
# define
标识符 lparen 标识符列表 , ... )
替换列表 换行符
# define
identifier lparen identifier-listopt )
replacement-list new-line
# define
identifier lparen ... )
replacement-list new-line
# define
identifier lparen identifier-list , ... )
replacement-list new-line
...
lparen:
(
字符,不能紧跟在空格后面
lparen:
a (
character not immediately preceded by white-space
有了空格,您将得到一个类似于对象的宏,该宏将扩展为(a,b) (a[b-1])
.
With the space, you get an object-like macro that expands to (a,b) (a[b-1])
.
(为增强鲁棒性,还建议在参数中加上括号,以便在传递更复杂的表达式时也可以使用.)
(For additional robustness, it's also recommended to parenthesize the parameters so that it also works if you pass in more complex expressions.)
这篇关于类似函数的宏的错误扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!