了解C中的宏 [英] Understanding macros in C

查看:61
本文介绍了了解C中的宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下代码的输出值为5?

Why is the output from the following code the value 5?

#include<stdio.h>

#define A -B
#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A);
  return 0;
}


推荐答案

这是一个棘手的问题,因为

This is a tricky question because it is a stress test for the compiler preprocessor.

取决于预处理器是编译器的集成阶段还是通过文件或文件将其输出传递给编译器的单独程序。管道,在这种情况下,是否足够小心不要执行错误的令牌粘贴,您可能会得到预期的输出: 5 ,否则可能会遇到编译错误。

Depending if the preprocessor is an integrated phase of the compiler or a separate program passing its output to the compiler via a file or a pipe and in this case whether it is careful enough to not perform erroneous token pasting, you may get the expected output: 5 or you may get a compilation error.

stdio.h 的预处理内容之后,源代码扩展为:

After the preprocessed contents of stdio.h, the source code expands to:

int main()
{
  printf("The value of A is %d\n", --5);
  return 0;
}

但是两个-是单独的标记,因此取决于预处理器是否在输出中将它们分开,您可能会得到一个程序,该程序输出 5 或由于<$ c $而无法编译的程序c>-不能应用于文字 5

But the two - are separate tokens, so depending if the preprocessor separates them in its output or not, you may get a program that outputs 5 or one that does not compile because -- cannot be applied to a literal 5.

两个 gcc clang 预处理器的行为正确,并且将-与当它们使用 -E 命令行选项生成预处理器输出时,要留有多余的空间以防止令牌粘贴。在扩展< stdio.h> 之后,它们将其输出为预处理的源代码:

Both the gcc and the clang preprocessors behave correctly and separate the - with an extra space to prevent token pasting when they produce the preprocessor output with the -E command line option. They output this as preprocessed source code after the expansion of <stdio.h>:

int main()
{
  printf("The value of A is %d\n", - -5);
  return 0;
}

尝试使用自己的编译器检查其如何扩展源代码。似乎Visual Studio 2013和2015无法通过测试并拒绝程序并出现错误。

Try your own compiler to check how it expands the source code. It seems Visual Studio 2013 and 2015 fail the test and reject the program with an error.

为了使事情变得清楚,我不说程序的行为应取决于编译器架构。我希望至少有一个普通的C编译器会误处理此一致性测试。我不惊讶MS Visual Studio 2013和2015未能通过该测试。

To makes things clear, I do not say the behavior of the program should depend on the compiler architecture. I was hoping at least one common C compiler would mishandle this conformance test. I am not surprised MS Visual Studio 2013 and 2015 fail this test.

仅预处理器的文本输出中需要的额外空间。 Visual Studio是否使用多个单独的阶段都没有关系,源程序是完全有效的,而编译失败则是BUG。

The extra space in only needed in the textual output of the preprocessor. It does not matter if Visual Studio uses multiple separate phases or not, the source program is perfectly valid and their failure to compile it is a BUG.

这篇关于了解C中的宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆