Search code examples
delphiblock

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.

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?


Solution

  • 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.