0

When i put a semi colon after while in this code

#include <iostream>
using namespace std;
int main(){
    int i = 1, n =1 ;
    while (i > 10);{
        cout << n << ") " << "Hello world! \n";
            i++;
            n++;
    } 
cout << "Hi world !";
    return 0;
} 

Why does it print Hello world! once and then Hi world! is it just useless and why ?

  • 3
    `while (i > 10);` is equivalent to `while (i > 10) {}`. – Jarod42 Dec 13 '21 at 16:20
  • Since `i` is `1`, the `while (1 > 10)` is `while (false)`. So that part is what I'd consider useless, but sometimes code is "useless" while it is in the midst of being crafted. When I have a null statement for a loop (not very common), in order to make it more visible one could do `while (i > 10) continue;` (helps indicate that it was not a typo or oversight, but rather it was intentional). – Eljay Dec 13 '21 at 16:24
  • "Is it useless" is hilarious because that implies it's something people actually do. It's not. It's bad code. You separated your while statement from the loop body, and the *only* reason you didn't get stuck in an invisible infinite loop is because your loop's Boolean expression is using the wrong comparator. – sweenish Dec 13 '21 at 16:25
  • The grammar of a `while` loop is `while (condition) statement`. Usually a compound statement is used--that's the `{ ... }` block. However, `;` by itself is a statement: It is a [null statement](https://en.cppreference.com/w/cpp/language/statements#Expression_statements) and it does nothing. – Nathan Pierson Dec 13 '21 at 16:25
  • Compilers will [warn](https://godbolt.org/z/7q1r9PssK) about this code not doing what you want. Get into the habit of enabling as many warnings as you can. – cigien Dec 13 '21 at 16:26
  • ok ,the part that ` while (1 >10) ` was actually intended because i wanted to see if it wont execute the code at all or not – Youssef Mohamed Dec 13 '21 at 16:32

1 Answers1

2

The semicolon after the while statement means a null statement. That is the sub-statement of the while statement is the null statement.

So in fact you have

while (i > 10) /* null statement*/;

/* compound statement */
{
    cout << n << ") " << "Hello world! \n";
        i++;
        n++;
} 

As initially i is not greater than 10 then the while loop will not be executed and the control will be passed to the compound statement. where the string "Hello world!" is outputted.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Just a thought, but perhaps you could check to see if the question is a duplicate before answering? For questions like this one, it's rather unlikely that it's never been asked before, and there's no value to answer them again. If you do have a novel answer, you should definitely post it on the target. – cigien Dec 13 '21 at 16:28