Putting semicolons after while and if statements in C++


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).

Updated on: 11-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements