递归注释的语言支持
我使用过的大多数语言都不支持递归注释。
- 语言设计者有什么理由选择不实现这个呢?
- 是不是很复杂?
- 会不会产生不良结果?
递归注释的示例:
/*
for (int j = 0; j <= SourceTexture.Height; j += SampleSize)
{
...
}
// Comment within comment below:
/*for (int i = 0; i < TextureColour.Length; i++)
{
...
}*/
sourceTexture.SetData<Color>(TextureColour);
*/
编辑:我理解到目前为止答案的论点(当字符串中有注释标记时会出现问题)。然而,我困惑的原因是你现在遇到了这个问题。
例如,我知道下面的代码不会给出预期的结果。
/*
char *str = "/* string";
// Are we now 1 level inside a comment or 2 levels?
*/
printf("Hello world");
/*
char *str2 = "string */";
*/
但在我看来,这与以下情况下的意外结果没有什么不同:
/*
CODE "*/";
*/
这也会产生意外/不期望的结果。
因此,虽然这可能是递归注释的问题,但我关于为什么这不是不这样做的理由的论点是,这已经是非递归注释的问题。作为一名程序员,我知道编译器的行为是这样的,并且我会解决它。我认为用递归注释解决同样的问题并不需要付出更多的努力。
Most languages I've worked with don't have support for recursive comments.
- Is there any reason why language designers would choose not to implement this?
- Is it deceptively complex?
- Would it have undesired results?
Example of a recursive comment:
/*
for (int j = 0; j <= SourceTexture.Height; j += SampleSize)
{
...
}
// Comment within comment below:
/*for (int i = 0; i < TextureColour.Length; i++)
{
...
}*/
sourceTexture.SetData<Color>(TextureColour);
*/
EDIT: I understand the argument of the answers so far (problems occur when you have comment tokens in strings). However, the reason for my confusion is that you have that problem now.
For example, i know the code below wouldn't give the expected result.
/*
char *str = "/* string";
// Are we now 1 level inside a comment or 2 levels?
*/
printf("Hello world");
/*
char *str2 = "string */";
*/
But in my mind that's no different to an unexpected result in the case below:
/*
CODE "*/";
*/
Which would also yield an unexpected/undesired result.
So, while it could be a problem for recursive comments, my argument as to why that's not a reason not to do it, is that it is already a problem for non-recursive comments. As a programmer i know the compiler behaves like this and i work around it. I don't think it's much more effort to work around the same problem with recursive comments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(4)
虽然C的多行注释不能嵌套,但是在C中使用#if 0 ... #endif
或多或少可以达到递归注释的效果(我强烈建议你使用当你想要禁用一段代码时,正是出于这个原因)。
即使是设计得像帖子一样愚蠢的 C 预处理器也完全能够处理嵌套注释,就像它必须能够处理带有错误条件的嵌套 #if
指令一样。因此,这实际上与难以定义或解析的任何事情无关,因为尽管它使注释变得更加复杂,但它们仍然不会比预处理中完成的其他事情更复杂。
但是,使用 #if 0 ... #endif
当然要求您尝试排除的代码中不存在任何不匹配的 #endif
。
从根本上来说,注释不能同时是(a)完全非结构化和(b)递归的。无论是偶然还是有意的选择,C 都选择了 (a)——注释文本不必遵守任何语法约束,除了不包含注释终止符序列(或等价的三字符组,例如 *??/< ;换行符>/
)。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
这使得词法分析更加难以实现。
恕我直言,不,但这是主观的。
很难说。您已经发现,即使是普通的块注释也会产生问题:
我知道有 2 种具有嵌套块注释的语言: Haskell 和 弗雷格。
It makes the lexical analysis more difficult to implement.
IMHO, no, but this is subjective.
Hard to tell. You have already discovered that even normal block comments can make problems:
I know 2 languages that have nesting block comments: Haskell and Frege.