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?
Do not use a semicolon on the same line as an if , for , or while statement because it typically indicates programmer error and can result in unexpected behavior.
Control statements ( if , do , while , switch , etc.) do not need a semicolon after them, except for do ...
if you put a semicolon directly after the condition in an if statement, Java thinks it's finished with the body of the statement. The indentation of the next line, which is so important to human readers, is ignored by Java.
The #define directive is used to define values or macros that are used by the preprocessor to manipulate the program source code before it is compiled. Because preprocessor definitions are substituted before the compiler acts on the source code, any errors that are introduced by #define are difficult to trace.
There is a difference between semi-colons in Pascal and in C and their derivatives.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With