Sunday, April 6, 2014

back to semicolons for a moment

Someone asked me in a comment to Why Programming Languages Should Die what is the difference between semicolons used as statement separators and semicolons used as statement terminators. The difference is basically the difference between the period and the comma in English. You use a period to terminate a sentence and you use a comma to separate phrases.

When semicolons are used as statement terminators, there are certain statements that require a semicolon at then end, such as expression statements in C:

a = b+c;
function_call(a,b);

There are other statements that do not require a semicolon at the end, specifically compound statements:

if (a) {do_something();}
a = b+c;

You never need a semicolon after a compound statement like that, even if there is another statement following it. In Pascal, statements are used as separators. An assignment doesn't need a semicolon after it if it comes at the end of a block. In Pascal, blocks are surrounded with begin and end rather than braces, so this is legal:

begin
  a := b
end

But semicolons are needed between statements so you need a semicolon after an assignment if it has another statement following it, and you also need one after end if another statement follows it:

begin
  a := b;
  begin
    a := c
  end;
  a := d
end

So although the semicolon-as-separator makes a lot of intuitive sense, it is odd in practice and programmers tend to forget them or put them in the wrong places more often than they do with languages where the semicolon is just used to end certain statement types.