What is wrong with my if-statement?

Now I'm trying to explore pascal. And I ran into some compiler errors. I wrote an if else if statement:

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 this gives me an error on the first else :

";" expected but found "ELSE"

I searched 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 remove begin and end , but the same error occurred. Is this a compiler error?

PS I do this in a statement of case. But I do not think this is important.

+5
source share
1 answer

; not allowed before else in most 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 to use begin ... end brackets to avoid misunderstanding the code in complex if then else . something like this would 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 delete begin and end , since the semicolon before else . This will compile without errors:

  if ((input = 'y') or (input = 'Y')) then writeln('blah blah') else begin end; 

Added to comment by @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 unclear here if DoSmth3 is called on not (expr2) or (expr2) and (not (expr3)) . Although we can predict the behavior of the compiler in this example, more complex code without begin ... end becomes a hindrance to errors 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 behavior of the code is obvious.

+9
source

Source: https://habr.com/ru/post/1232892/


All Articles