Putting semicolons after while and if statements in C++

C++ProgrammingObject Oriented Programming

When you have a statement like −

while (expression);

the while loop runs no matter if the expression is true or not. However, if you put −

if (expression);

the statement runs no matter if the expression is true or not. This is because the syntax for if and while is −

if (<expr>) <statement>
// or
while (<expr>) <statement>

So the <statement> is only executed if the <expr> evaluates to true. In while, it will enter an infinite loop.

So the question what <statement> it executes. If there are not braces {} then the next statement is terminated by; even if that statement is EMPTY. Note that an empty statement is valid.

if (<expr>)    /* Empty Statement */;
while (<expr>) /* Empty Statement */;

In both cases, there is nothing being executed (after the expression is evaluated). Though while may enter an infinite loop. Note: '{}' is a statement-Block (a type of statement (that contains a list of other statements).

raja
Published on 15-Feb-2018 18:50:10
Advertisements