If Statement

Use the keyword if to implement a conditional statement. The syntax of the if statement has the following form:

if expression then statement1 [else statement2]

If expression evaluates to true then statement1 executes. If expression is false then statement2 executes. The expression must convert to a boolean type; otherwise, the condition is ill-formed. The else keyword with an alternate statement (statement2) is optional.

There should never be a semicolon before the keyword else.

Nested if statements

Nested if statements require additional attention. A general rule is that the nested conditionals are parsed starting from the innermost conditional, with each else bound to the nearest available if on its left:

if expression1 then
if expression2 then statement1
else statement2

The compiler treats the construction in this way:

if expression1 then
begin
  if expression2 then statement1
  else statement2
end

In order to force the compiler to interpret our example the other way around, we have to write it explicitly:

if expression1 then
begin
  if expression2 then statement1
end
else statement2
Copyright (c) 2002-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code