[英]Incorrect expansion of a function-like macro
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).我应该想出一个宏ENTRY
,它将一个值放入一个数组中(给出了scanf("%d",&ENTRY(x,i))
)。
I tried: #define ENTRY (a,b) (a[b-1])
, but that didn't work.我试过: #define ENTRY (a,b) (a[b-1])
,但这没有用。
It created a compiler error that says, that a and b are undeclared.它创建了一个编译器错误,指出 a 和 b 未声明。
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.但我认为我不必声明宏中使用的变量,尤其是因为,例如: #define min (a,b) ((a)<(b)?(a):(b))
在另一个程序。
So what am I doing wrong here?那么我在这里做错了什么?
#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
6.10 – Preprocessing directives : 6.10 – 预处理指令:
... ...
control-line:控制线:
... ...
# define
identifier lparen identifier-listopt)
replacement-list new-line# define
标识符lparen identifier-listopt)
替换列表换行# define
identifier lparen... )
replacement-list new-line# define
标识符lparen... )
替换列表换行# define
identifier lparen identifier-list, ... )
replacement-list new-line# define
标识符lparen identifier-list, ... )
替换列表换行... ...
lparen: lparen:
a(
character not immediately preceded by white-space a(
字符前面没有空格
With the space, you get an object-like macro that expands to (a,b) (a[b-1])
.使用空间,您将获得一个类似对象的宏,该宏扩展为(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.) (为了额外的健壮性,还建议将参数括起来,以便在您传入更复杂的表达式时也能正常工作。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.