I
last month
Iancountry asked

Why do we use while (1) in C/C++, and what does it mean?

Abhay Jajodia
Expert
last month
Abhay Jajodia answered

Hello Ian, really nice question.

In C and C++, a while loop keeps running as long as its condition is true.
The key detail is: in C/C++, any non-zero value is treated as true, and 0 is treated as false.

So when you write:

while (1) {
    // loop body
}

the condition 1 is always true. There’s nothing inside the parentheses that can change over time – it’s just the constant value 1. That means the loop is set up to run forever, unless you manually stop it using something like break, return, or exiting the program.

In your example:

while (1) {
    cin >> number;

    if (number <= 0) {
        break;              // this is what actually stops the loop
    } else {
        total = total + number;
    }
}

What’s happening is:

  1. while (1) creates an infinite loop.

  2. Inside the loop, you read a number.

  3. If the number is 0 or negative, you hit break, and that’s what exits the loop.

  4. Otherwise, you keep adding to total and go around again.

So the idea is:

  • while (1) = “keep looping until I decide to stop using break.”

  • The real stop condition is written inside the loop, not in the while parentheses.

In modern C++, you’ll also see people write while (true) instead of while (1). They mean the same thing in this context, it’s just a bit more readable.

If you have further questions, I'm here to help.

C++
This question was asked as part of the Learn C++ Basics course.