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.
CodePudding user response:
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)
CodePudding user response:
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;
}