I am pretty new at coding and have no idea the benefits/drawbacks/differences between then *insert code*
and then begin *insert code*
.
if ... then
...
if ... then
begin
I am pretty new at coding and have no idea the benefits/drawbacks/differences between then *insert code*
and then begin *insert code*
.
if ... then
...
if ... then
begin
Delphi needs begin
and end
to form blocks. It does not keep blocks of code together by indentation, like e.g. Python does, it uses begin
end
to delineate these blocks. Languages like C, C++, C#, Java and JavaScript use {
and }
instead, for the same purpose.
In Pascal, the if-statement is as follows:
if <condition> then operation1
or, if there is an else-clause:
if <condition> then operation1 else operation2
Where <condition>
can be any expression that has a boolean result
The operation can be a single statement, e.g.
Writeln('Hello')
or it can be a so called compound statement, which is a begin-end block with multiple statements inside (although zero or one statements are also allowed), e.g.:
begin
Writeln('Hello');
Writeln('World!')
end
So the difference is not between then
and then begin
, but between single statements and compound statements. An, admittedly rather simple, example:
if NeedOneLine then
Writeln('Hello, World!') // single statement
else
begin // compound statement: multiple statements enclosed
Writeln('Hello,'); // in "begin" and "end"
Writeln('World!');
end;
The above code either writes one line or two lines. The following code, that does not use begin end, looks similar, but has a totally different result:
if NeedOneLine then
Writeln('Hello, World!')
else
Writeln('Hello,');
Writeln('World!');
That will either write 'Hello, World!'
or 'Hello,'
and always be followed by 'World!'
, because it is exactly the same as:
if NeedOneLine then
Writeln('Hello, World!')
else
Writeln('Hello,');
Writeln('World!');
In other words, the last line is not part of the if-statement anymore and will be executed unconditionally. That is why begin
and end
are important here.