-2

i am having a very silly but strange problem. When i am trying to compile and run the following code my compiler is printing "ggl" but i think it shouldn't. It is strange that after doing so much programming i am stuck here. What exactly is the problem? Can someone please help me out? Thanks in advance !!

#include <iostream>
using namespace std;

int main() {
    int t=8;
    if(1<t<5){
        cout<<"ggl";
    }
    //cout<<aa;
    return 0;
}
varunkr
  • 5,364
  • 11
  • 50
  • 99

3 Answers3

5

This line doesn't do what you think it does

 if(1<t<5)

You would have to say

 if (1 < t && t < 5)

The first version says

if ((1 < t) < 5)

Which evaluates to

if (true < 5)
if (1 < 5)

Which is always true.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • We appear to be typing the same things at the same time. I'll +1 yours anyway. – abligh Jan 11 '15 at 15:47
  • Thanks Cyber for the quick response !! Is this (1 – varunkr Jan 11 '15 at 15:54
  • @varunkr In general, most languages have the behavior that you just saw for the reason I described. One exception that comes to mind is `Python` that allows the syntax you originally wrote. – Cory Kramer Jan 11 '15 at 15:55
4

Your if condition effectively says if ((1 < t) < 5), which is always true, because (1 < t) is either 1 or 0 (1 < 8 evaluates to 1).

Since chained comparisons do not (usually) work in C++, you'll need to check the condition differently:

if (1 < t && t < 5) {
    cout << "ggl";
}
vaultah
  • 44,105
  • 12
  • 114
  • 143
2

This

if(1<t<5)

does not do what you think it does. It does not determine whether t is between 1 and 5. You want

if ((1<t) && (t<5))

What it actually does is take the value (1<t) (which will 1 if 1<t and 0 otherwise), then see if that value is less than 5, which it always will be.

abligh
  • 24,573
  • 4
  • 47
  • 84