为什么要“单一声明”?块不需要使用分号?
我通常是一名 C# 程序员,使用 Delphi 充满了“有趣”的发现。最让我困惑的是 Delphi 中的单个语句。
C# 块示例
if(x)
Foo();
else
Bar();
Delphi 块示例:
if x then
Foo() //note missing semicolon
else
Bar();
要求不存在分号的确切目的是什么?是否有可以追溯到帕斯卡的历史原因?
I'm usually a C# programmer and going to Delphi has been full of "interesting" discoveries. The one that baffles me the most is single statements in Delphi.
Example C# block
if(x)
Foo();
else
Bar();
Example Delphi block:
if x then
Foo() //note missing semicolon
else
Bar();
What exactly was their purpose for requiring that semi-colon to not be there? Is there a historical reason dating back to Pascal?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Pascal 和 C 及其派生语言中的分号之间存在差异。
维基百科解释了这一点的含义:
There is a difference between semi-colons in Pascal and in C and their derivatives.
Wikipedia explains the implications of this:
;
不允许出现在 if-thenelse
前面的真正原因是为了避免与其鲜为人知的表亲 产生歧义。 case-ofelse
。观察以下代码片段:
因为在
'oops'
行后面有一个;
,所以else
属于case
> 语句而不是if
。如果省略
;
,则else
属于if a=1
。这就是为什么
;
不允许出现在if
else 前面。个人曾在 Pascal 中工作过二十多年来,我仍然把
;
放在else
前面,因为我把;
放在 C 风格中。编译器仍然困扰着我,你认为编译器现在应该已经学会了。The real reason
;
is not allowed in front of a if-thenelse
is to avoid ambiguity with its lesser known cousin, the case-ofelse
.Observe the following snippet:
Because there is a
;
after the'oops'
line, theelse
belongs to thecase
statement and not theif
.If you leave out the
;
then theelse
belongs to theif a=1
.That's why a
;
is not allowed in front of anif
else.Personally having worked in Pascal for some 20-odd years, I still put
;
in front ofelse
, because I put;
in C-style. And the compiler still bugs me, you'd think the compiler would have learned by now.