0

I was trying to look up on to some basics i stumbled on this problem where I was required to give a condition and print a statement based on whether the number was odd or even.

Here's the first code : https://ideone.com/vS8wgs

#include <iostream>
using namespace std;

int main() {



  int x = 18;


   if(x%2 == 0 && 2<=x<=5){

    cout << "x lies between 2 and 5" << endl;

   }
   if(x%2 == 0 && 6<=x<=20){

    cout << "x lies between 6 and 20" << endl;

   }

    return 0;
}

Answer to the first one turns out to be :

x lies between 2 and 5
x lies between 6 and 20

Here the second variant : https://ideone.com/rQ7KoW

#include <iostream>
using namespace std;

int main() {


int x =18;

 if(x%2 == 0 && x >= 2 && x <=5){

    cout << "x lies between 2 and 5" << endl;

   }

   if(x%2 == 0 && x >= 6 && x<=20){

    cout << "x lies between 6 and 20" << endl;

   }

    return 0;
}

Answer to the Second one turns out to be :

x lies between 6 and 20

Up until now i was assuming both would return the same result, I would like to know the reason for both not having same functionality.

xAditya3393
  • 149
  • 4
  • 12
  • 2
    `2 <= x` is a boolean expression which may logically be represented by `0` or `1`. Then that is tested `<= 5` and both `0` and `1` are always less than `5`, right? – James Adkison May 26 '16 at 20:40
  • `a <= b <= c` is left associative, so it means really, `(a <= b) <= c`, which boils down to `0 <= c` or `1 <= c` which is always true in your case. – Orange Mushroom May 26 '16 at 20:42
  • Got my answer guys ... just checked out the question Fred Larson marked.. The statement (2<=x<=5) is being interpreted as ((2<=x) <= 5) which makes the results turn out as they have turned out to be ... Kinda embarrassing answering my own question – xAditya3393 May 26 '16 at 20:49

0 Answers0