1

I have the following code in C++:

(where arr.data[i-1] = 20; arr.date[i] = 30; payload = 50;)

if (i > 0 && arr.data[i-1] < payload < arr.data[i]) {
    cout << arr.data[i-1] << " < " << payload << " < " << arr.data[i] << "\n";
}

and I am getting the statement returned as

20 < 50 < 30

What am I doing incorrect?

biw
  • 3,000
  • 4
  • 23
  • 40
  • Use a compiler with warnings enabled! See [Coliru example here](http://coliru.stacked-crooked.com/a/2f02d1c30f9b7b3f). – Csq Sep 22 '14 at 00:23

2 Answers2

7

You can't chain comparison operators like this:

if (i > 0 && arr.data[i-1] < payload < arr.data[i]) {

Instead, it should look like this:

if (i > 0 && arr.data[i-1] < payload && payload < arr.data[i]) {

Note that you do this in a few places in your code.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
1

Relational operators in C++ are left associative, so this is how the implementation reads it:

(i > 0 && arr.data[i-1] < payload) = TRUE = 1 (Boolean logic)

so, (1 < arr.data[i]) = TRUE

Manol
  • 11
  • 1