0

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.

  • Check this thread: http://stackoverflow.com/questions/4276207/is-c-c-bool-type-always-guaranteed-to-be-0-or-1-when-typecasted-to-int – taocp Dec 16 '13 at 22:34

5 Answers5

2

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

Paladine
  • 513
  • 3
  • 11
  • Ah ok, I thought it was something to do with that but just wasn't 100% sure. Thanks for your answer :) – BroooksyBearx Dec 16 '13 at 22:36
  • The C++ library is smart enough to parse an integer as a boolean. So when the user types 0, it knows to set condition to `false` – Paladine Dec 16 '13 at 22:40
  • I wouldn't say it's how "boolean logic works". I'd say it's how "boolean logic works *in c/c++*". I grew up on c++, so it surprised me how many other languages just don't let you coerce ints into bools like that. – neminem Dec 16 '13 at 22:40
  • @neminem See my comment above yours. It's really how the C++ standard library knows how to parse integers into booleans. – Paladine Dec 16 '13 at 22:43
1

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

Captain John
  • 1,859
  • 2
  • 16
  • 30
1

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.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

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.
Ali Raza
  • 191
  • 2
  • 12
-1

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)

Luke
  • 317
  • 2
  • 6
  • 17
  • This will never end. (Or until shutdown. Whatever comes first.) – Jongware Dec 16 '13 at 23:05
  • An assignment always returns its new value, in your case `true`. So your loop is `{ .. } while (true);` -- boiler-plate Neverending Story code. – Jongware Dec 16 '13 at 23:12