解释使用以下宏获得的输出

问题描述 投票:-7回答:1
#include <stdio.h>

#define ABC(x) DEF(x)
#define DEF(x) GHI(x)
#define GHI(x) printf(x)

int main(void)
{
  int x = 100;
  int y = 200;
  ABC(("Sum of x + y is %d", x + y));

  return 0;
}

上面代码的输出给出了无效的内存引用(SIGSEGV)。

c data-structures macros c-preprocessor
1个回答
1
投票

如果您已经考虑过警告,那么您可以自己确定

macro1.c: In function ‘main’:
macro1.c:11:3: warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast [enabled by default]
   ABC(("Sum of x + y is %d", x + y));
   ^
In file included from macro1.c:1:0:
/usr/include/stdio.h:362:12: note: expected ‘const char * __restrict__’ but argument is of type ‘int’
 extern int printf (const char *__restrict __format, ...);
            ^
macro1.c:11:3: warning: format not a string literal and no format arguments [-Wformat-security]
   ABC(("Sum of x + y is %d", x + y));

这清楚地表明你将int而不是string传递给printf。因为预处理后您的代码将如下所示。

printf(("Sum of x + y is %d", x + y))

为了使其工作,您可以执行以下操作。

#include <stdio.h>

#define ABC(x,y) DEF(x,y)
#define DEF(x,y) GHI(x,y)
#define GHI(x,y) printf(x,y)

int main(void)
{
  int x = 100;
  int y = 200;
  ABC("Sum of x + y is %d", x + y);

  return 0;
}

或者你可以删除qazxsw poi中qazxsw poi周围的括号

x
© www.soinside.com 2019 - 2024. All rights reserved.