The shift operator has highest priority compared to the conditional operator. So the expression can be rewritten the following way
( cout<<(i<0) ) ? getch() : getch();
So the first getch will be executed because the value of the expression ( cout<<(i<0) ) which ihas type of std::ostream will be converted to const void * which will not be equal to zero if there was no any error.
there are at least 3 consecutive things happening with this expression.( cout<<(i<0) )
1. The first thing is the (i<0) test. The result will be a bool value of either true or false.
2. The next thing that happens is the cout << - this outputs the value of the first test obviously.
if you send a boolean value to a stream you will get 1 if the value is true or 0 if it is false - so you should see either a 1 or a 0 on the console screen.
3. The << function overload returns a reference to itself.
The last test is if this cout is true or false.
But how can a ostream (or istream) object be tested for truthness.
The ostream class keeps an internal record of it's current state - if you ask a stream to ouput or input some value and that operation fails then
the stream will set it's internal state to BAD - if it succeeded it will set it's state
The stream class also have a boolean operator overload function.
boolean overlaod functions allows a class to be used in an expression where
true or false is required such as an if statement:
if ( some_expression_to_be_tested_for_truth) //
If you put an ostream or istream object in such a position - it
will give a result of true if it's internal state is GOOD , or false if it is in a bad/failed state.
It is interesting to note that before the C++ 2011 there is no conversion operator to bool in stream classes. There is conversion operator to void * in the C++ Standard before 2011.
Now instead of operator operator void* the C++ Standard defines operator explicit operator bool.