Are comments always processed before the preproces

2019-06-24 09:55发布

This question already has an answer here:

/*
#define FOO
*/

#ifdef FOO
#define BAR "pirate"
#else
#define BAR "ninja"
#endif

int main() { printf(BAR); getchar(); }

In this code FOO is not defined (Visual Studio 2008). I assume that comments are processed first, then preprocessor, and then code. Are comments always processed before the preprocessor? Is this part of a standard?

6条回答
Bombasti
2楼-- · 2019-06-24 10:08

According to the C standard, there are 8 translation phases during translation (compilation) of a program. Each comment is replaced by a whitespace character in translation phase 3, whereas preprocessing directives are executed in phase 4.

查看更多
叛逆
3楼-- · 2019-06-24 10:12

Some quick research indicates that comments are converted to whitespace by the preprocessor. So, it's all part of the same flow.

According to Wikipedia, comments are handled before preprocessor directives.

查看更多
再贱就再见
4楼-- · 2019-06-24 10:24

Yes, the preprocessor replaces comments before handling directives.

From section 5.1.1.2 (Translation phases) of the C99 standard:

3) The source file is decomposed into preprocessing tokens and sequences of white-space characters (including comments).... Each comment is replaced by one space character....

4) Preprocessing directives are executed, macro invocations are expanded, ....

查看更多
该账号已被封号
5楼-- · 2019-06-24 10:25

Yes (in every sane universe).

查看更多
走好不送
6楼-- · 2019-06-24 10:32

I assume that comments are processed first, then preprocessor, and then code. Are comments always processed before the preprocessor?

Sort of -- part of the preprocessor's job is to remove comments. In this case, it doesn't care that you have the directive inside the comments; it's still removed just like any other comment.

查看更多
狗以群分
7楼-- · 2019-06-24 10:32

Yes, from the language standard point of view, comments are processed (replaced with spaces) before the preprocessor begins doing its work.

In practical implementations, processing of comments can be done by the same code (e.g. the same executable) that handles preprocessor directives and carries out macro substitution, but the result must be the same: comments have no effect on preprocessor proper.

In older and/or non-standard code sometimes one might see some tricks that rely on non-standard behavior involving implementation-specific comments vs. preprocessor relationships, like, for example, creation of comments using preprocessor directives

#define CONCAT(a, b) a##b
#define BEGIN_COMMENT CONCAT(/, *)
#define END_COMMENT CONCAT(*, /)

BEGIN_COMMENT
  This code is supposedly commented-out
END_COMMENT

or using comments for preprocessor-level concatenation (with C compilers that didn't support ## operator in macro definitions)

#define OLD_CONCAT(a, b) a/**/b

None of such tricks are legal in standard C. None of them really work.

查看更多
登录 后发表回答