Putting Semicolons After While and If Statements in C++



In C++, a semicolon(;) indicates the end of a statement in code, or we can say it terminates the statement. When you use a semicolon just after an if or while statement, it creates an empty statement, which executes nothing.

Semicolon with If Statement

In C++, the if statement is a conditional statement that runs only if the condition is true, where {} braces are used to write the condition inside them.

But if you use a semicolon just after the if statement, it will still check the condition, but it controls just an empty operation; therefore, nothing will happen whether the condition is true or false, as the block {} is no longer dependent on the condition.

#include <iostream>
using namespace std;

int main() {
    int number = 10;

    if (number > 0); // <- this semicolon ends the if-statement!
    {
        cout << "The number is positive." << endl;
    }

    return 0;
}

Output

The number is positive.

Here, a semicolon (;) after the if condition terminates the if statement loop. Therefore, it means the {} block of code is not part of the if statement anymore; it's an independent block that will always execute regardless of the if condition.

Semicolon with While Statement

Similarly, when you place a semicolon just after a while loop, it will become an empty loop body, which means it will still check the condition, but it will execute nothing.

#include <iostream>
using namespace std;

int main() {
    int count = 0;

    while (count < 5);  // <- This semicolon creates an empty loop body!
    {
        cout << "This will print only once!" << endl;
        count++;
    }

    return 0;
}

In this, the semicolon(;) ends the loop immediately; therefore, it terminates the loop body. So, while (count < 5); is a loop with an empty body, which makes it an infinite loop because count is never updated inside the loop. As the block code is no more part of the while loop, it becomes a separate block.

if (condition) statement;
while (condition) statement;

In this case, when you don't use {}, then only one statement will be executed just after the condition check, and the next statement is terminated by; even if that statement is EMPTY. '{}' is a statement block that contains a list of other statements. So you can avoid using {} when working with a single operation.

Updated on: 2025-04-23T19:19:08+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements