if
cond stmt
if
cond block else
block
while
cond stmt
do
stmt while
cond
cond is expression of type bool. (therefore
int i=10; while (i--) f();
is not allowed, one needs to write
while (i-- != 0)
). stmt might be single statement or
a block. block is zero or more stmt's surrounded
with { }
. One might note that if's version with else
keyword is required to have { }
around each part. This is to
solve dangling-else problem, for example:
C:
if (b1) if (b2) f1(); else f2();
This if of course parsed as:
if (b1) { if (b2) { f1(); } else { f2(); } }
In C else
is associated with nearest else-free if
.
As you have seen this can be source of problems.
However, as there is no danger with using if
without { }
and
else
, (as in if (x == 0) x++;
), it can be used without
{ }
.