I am now trying to explore pascal. And I ran into some compiler errors. I wrote a if else if statement like this:
if ((input = 'y') or (input = 'Y')) then
begin
writeln ('blah blah');
end;
else if ((input = 'n') or (input = 'N')) then
begin
writeln ('blah');
end;
else
begin
writeln ('Input invalid!');
end;
And it gives me an error at the first else
:
";" expected but "ELSE" found
I looked for a lot of tutorials about if statements and they just do it like me:
if(boolean_expression 1)then
S1 (* Executes when the boolean expression 1 is true *)
else if( boolean_expression 2) then
S2 (* Executes when the boolean expression 2 is true *)
else if( boolean_expression 3) then
S3 (* Executes when the boolean expression 3 is true *)
else
S4; ( * executes when the none of the above condition is true *)
I tried to delete the begin
and end
but the same error occured. Is this a compiler bug?
P.S. I am doing this in a case statement. But I don't think it matters.
;
is not allowed beforeelse
in the majority of cases.will compile. But... Prefer using
begin
...end
brackets to avoid misunderstanding of code in complicatedif then else
statements. something like this will be better:The second sample is much easier to read and understand, isn't it?
The code does not work when you remove
begin
andend
because there is a semicolon beforeelse
. This will compile without errors:Appended on comment of @lurker
Please, see the following example without
begin
...end
brackets.It is not clearly seen here, if
DoSmth3
is called onnot (expr2)
or(expr2) and (not (expr3))
. Though we can predict the compiler behaviour in this sample, the more complicated code withoutbegin
...end
becomes subect to mistakes and is difficult to read. See the following code:Now the code behavior is obvious.