0

Possible Duplicate:
How would std::ostringstream convert to bool?

#include<iostream.h>
 void main() {
   if(cin>>2) {    // what is cin>>2 doing inside arg of if
      cout<<"if works";
   } else {
       cout<<"else works";
     }
 }

We don't get error in this code.But Alwaysif statement works why? how?

Community
  • 1
  • 1
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • It is evaluated like any other expression, apparently to a non-zero value. – Mr. Shickadance Apr 17 '11 at 17:38
  • 1
    and `void main()` is deprecated, it should be `int main()`. And you either need a `using std::cout; using std::cin;` or `using namespace std;` before the first use of `cin` or `cout`. – rubenvb Apr 17 '11 at 17:43
  • I have compiled this using turbo-c++ – Suhail Gupta Apr 17 '11 at 17:43
  • 1
    This does not compile for me. And there are so many other warnings (like the use of iostream.h) which indicate you are probably using an ancient compiler. – Martin York Apr 17 '11 at 20:27

2 Answers2

4

cin >> 2 is invalid. cin >> integervar is valid, assuming that's what you mean?

The standard library class ios which basic_istream (and thus cin) inherits from overloads operator void * (and operator!) to allow you to do such tests.

operator void * returns 0 if failbit or badbit is set - aka the last extraction failed.

This is the "standard" way of combining extraction and checking if the extraction succeeded.

Erik
  • 88,732
  • 13
  • 198
  • 189
2
if(cin>>2) 

This wouldn't even compile. See this : http://ideone.com/MiEkq

What you probably mean is : if(cin>>var)

If that is so, then it means IF the read from the input stream succeeds, then then if block will be executed because after successful read, the returned std::istream & can implicitly convert into true, otherwise it converts into false.

BTW, the return type of main() should be int.

Nawaz
  • 353,942
  • 115
  • 666
  • 851