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 before else
in the majority of cases.
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;
will compile.
But... Prefer using begin
... end
brackets to avoid misunderstanding of code in complicated if then else
statements.
something like this will be better:
if ((input = 'y') or (input = 'Y')) then
begin
writeln('blah blah');
end
else
begin
if ((input = 'n') or (input = 'N')) then
begin
writeln('blah');
end
else
begin
writeln('Input invalid!');
end;
end;
The second sample is much easier to read and understand, isn't it?
The code does not work when you remove begin
and end
because there is a semicolon before else
. This will compile without errors:
if ((input = 'y') or (input = 'Y')) then
writeln('blah blah')
else
begin
end;
Appended on comment of @lurker
Please, see the following example without begin
... end
brackets.
if expr1 then
DoSmth1
else if expr2 then
if expr3 then
DoSmth2
else
DoSmth3;//Under what conditions is it called?
It is not clearly seen here, if DoSmth3
is called on not (expr2)
or (expr2) and (not (expr3))
. Though we can predict the compiler behaviour in this sample, the more complicated code without begin
... end
becomes subect to mistakes and is difficult to read. See the following code:
//behaviour 1
if expr1 then
DoSmth
else if expr2 then
begin
if expr3 then
DoSmth
end
else
DoSmth;
//behaviour 2
if expr1 then
DoSmth
else if expr2 then
begin
if expr3 then
DoSmth
else
DoSmth;
end;
Now the code behavior is obvious.
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