uksz
uksz

Reputation: 18719

C++: Issue with lambda function and capture list

I have the following function:

double mn = 2.0;
double mx = 5.0;
auto isBetween = [&,mx,mn](double y) -> bool{
    if (mn<y<mx) {
        return true;
    } else {
        return false;
    }
};

However, when I debug, all of the values I pass as double y return true.

Is there anything that I am missing?

Upvotes: 0

Views: 59

Answers (3)

Rabbid76
Rabbid76

Reputation: 210998

Your Problem is here (mn<y<mx), which can be read as

(mn < y) < mx

This means, that first mn < y is evaluated, which leads in a result of type bool and is either ture or false. The result is finally compared to mx.

What you tried to do is to check, if mn < y and y < mx, what has to be expressed like this:

if (mn<y && y<mx)

Upvotes: 1

Throw Away Account
Throw Away Account

Reputation: 2671

In C++, the < operator cannot be chained the way it can in mathematics. In the expression (mn < y < mx), (mn < y) evaluates to either 1 (true) or 0 (false), and from there the expression is equivalent to 1 < mx or 0 < mx.

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490218

Your test if (mn<y<mx) isn't what you want.

You want something like: if (mn < y && y < mx) instead.

Upvotes: 4

Related Questions