BroooksyBearx
BroooksyBearx

Reputation: 21

Confused at the following code

So I am currently learning how to code using C++. I came across the following code below.

    // =======================
    // Lesson 2.4.3 - Do while
    // =======================

    #include<iostream>
    using namespace std;

    int main()
    {
        bool condition = false;

        do
        {
        cout << "Enter a 0 to quit or 1 to continue: ";
        cin >> condition;
        }

        while (condition);
    }

Why is it that C++ automatically knows that 0 breaks the loop and that 1 continues the loop? Is it to do with a command knowing that 0 = false and that anything above is true? Thanks to those who can help.

Upvotes: 0

Views: 88

Answers (5)

Ali Raza
Ali Raza

Reputation: 189

A bool variable can have one two conditions i.e true or false. 0 is considered as false and any value other than 0 is considered as true. So the condition you have written is (when condition=true.

while(!0) // body opf while will execute

and when the condition=false it, c++ will interpret it like this

while(0)  // and body of do while will not execute.

Upvotes: 0

Pete Becker
Pete Becker

Reputation: 76523

The variable condition has type bool, so it's values can be true or false. When it's false the loop terminates. On input and output for a bool, 0 is false and 1 is true.

Upvotes: 1

Luke
Luke

Reputation: 317

because after the input is read the condition is checked while (condition);

while (condition = true);

the first code gets set to the above by default

This means the code in the body of the do while loop will loop while the condition value is true (1)

Upvotes: -1

Captain John
Captain John

Reputation: 2001

It's because while (0) evaluates to false therefore terminating the loop.

Upvotes: 1

Paladine
Paladine

Reputation: 523

That's just how boolean logic works. 0 is false, anything non-0 is true.

Upvotes: 2

Related Questions