If I use assignment operators or output functions inside the if condition, why is it taken as a "true" boolean value?
For example, I do
if(cout << "a"){cout << "c";}
Or
if(int x=7){cout << "c";}
Or even
if(6){cout << "c";}
the outputs are indeed, c and c and c in each case. But we were told that, inside the if condition, we have to use an expression that finally evaluates to a boolean value like 1 or 0.
So what is the piece of information I am missing?
Every value inside condition (or with boolean conversion) will give you true, unless it equal to 0.
In c you can see it with
NULL
with this declaration:which means that if an pointer equal to
NULL
it will return you a false in a boolean conversion.Examples in c++ for boolean expressions:
In all the cases you've shown, it's still true that you've provided an expression that eventually is convertible to
bool
. If you look at the<<
operator ofstd::cout
and similarostream
s, you'll see they all return a reference to the same stream. This stream also defines a conversion tobool
operator, which is implicitly called in a context where abool
is expected. This particular conversion returnstrue
if the stream has no errors. Secondly,int x=7
is an initialization, and it returns the value thatx
was just initialized with;7
in this case.int
in C++ can be implicitly cast to bool to betrue
if it's not zero, which is why both7
and6
evaluate to true in the second and third examples.In each case the expression is converted to a bool. The value of this bool is true in the three cases that you use (it may not always be true).
In this case the expression:
If find the
operator<<(std::ostream&, char const*)
definition you will find that the return value isstd::ostream&
. So this will return a reference to thecout
object (of type std::ostream). The stream object has a boolean conversion methodexplicit bool()
which can be used to convert the object to bool. The result of this depends on the state of the object (if it is in a bad (failing) state it will return false).So here you are checking that the last operation on the stream worked. If it does then print "c". This is commonly used on input streams to validate user intput.
In the other cases you use int variables. These can be implicitly converted to bool. If the value is non zero then it is true (otherwise false).