mikhailovich
mikhailovich

Reputation: 229

Question about bool in C++

I was wondering why the code below only returns "Test" four times, instead of five?

    #include <iostream>
    #include <cassert>
    using namespace std;

    class CountDown
    {
      public: //Application Programmer Interface
        CountDown(int start); // it is set to start
        void next(); // subtracts one from it
        bool end()const; //
     private:
        int it;
    };

    CountDown::CountDown(int start)
    {
        it = 0;
        it = start;
    }

    void CountDown::next()
    {
        it = it - 1;
    }

    bool CountDown::end() const
    {
        if (it <= 0)
          cout << "The countdown is now over" << endl;
    }

    int main()
    {
        for( CountDown i = 5 ; ! i.end(); i.next())
        std::cerr << "test\n";
    }

Upvotes: 0

Views: 200

Answers (2)

Marius Bancila
Marius Bancila

Reputation: 16338

There is no point in doing this double initialization:

CountDown::CountDown(int start)
{
    it = 0;
    it = start;
}

This is enough:

CountDown::CountDown(int start)
{
    it = start;
}

Or even this, using the initialization list:

CountDown::CountDown(int start):it(start)
{
}

As for end() you don't return any value from it. The method should probably look like this:

bool CountDown::end() const
{
    return it <= 0;
}

Upvotes: 4

Elmi Ahmadov
Elmi Ahmadov

Reputation: 1035

try this.

bool CountDown::end() const
  {
   if (it > 1) return false;
   return true;
  }

Upvotes: -1

Related Questions