开发者

Why do "single statement" blocks require not using semi-colons?

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.

Exam开发者_Go百科ple 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?


There is a difference between semi-colons in Pascal and in C and their derivatives.

  • In C the semi-colon is a statement terminator.
  • In Pascal the semi-colon is a statement separator.

Wikipedia explains the implications of this:

This difference manifests itself primarily in two situations:

  • there can never be a semicolon directly before else in Pascal whereas it is mandatory in C (unless a block statement is used)
  • the last statement before an end is not required to be followed by a semicolon

A superfluous semicolon can be put on the last line before end, thereby formally inserting an empty statement.


The real reason ; is not allowed in front of a if-then else is to avoid ambiguity with its lesser known cousin, the case-of else.

Observe the following snippet:

case enum1 of
  male: writeln('hallo');
  female: if a=1 then writeln('oops');  <<-- watch this space.
  else writeln('neither')
end; 

Because there is a ; after the 'oops' line, the else belongs to the case statement and not the if.

If you leave out the ; then the else belongs to the if a=1.

That's why a ; is not allowed in front of an if else.

Personally having worked in Pascal for some 20-odd years, I still put ; in front of else, because I put ; in C-style. And the compiler still bugs me, you'd think the compiler would have learned by now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜