简体   繁体   中英

variable declaration in while loop

using namespace std;

class Counter
{
    int val;

public:
    Counter() { val = 0; }
    int Next() { return ++val; }
};

int main()
{
    Counter counter;

    while (int c = counter.Next() <= 5)
    {
        cout << c << endl;
    }
}

When run, the program prints out 1 5 times. Thus, .Next() is returning the expected value as the while loop does terminate.

Why is the value of c remain set to the initial value?

I'm very new to C++ (this is the first C++ program I've written) and am just trying to understand how the return value of .Next() could be as expected and evaluated but not captured in the c variable.

The <= operator has a higher precedence than the = operator.

So, with

while (int c = counter.Next() <= 5)

The compiler interprets it as:

while (int c = (counter.Next() <= 5))

which assigns the result of the logical expression to c , which will be 1 while the expression holds true.

Try this instead:

int c;

while ((c = counter.Next()) <= 5)

You can add a conversion operator for Counter , and remove the need to declare an extra variable.

class Counter {
    int val_;
public:
    Counter() : val_(0) {}
    int Next() { return ++val_; }
    operator int () const { return val_; }
};

//...
    Counter counter;
    while (counter.Next() <= 5) {
        cout << counter << endl;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM