On Oct 9, 3:00 pm, northsolomon...@gmail.com wrote:
On Oct 9, 2:50 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
So if I'm correct then any value other than zero will evaluate
to TRUE in an if statement? Does it mean that if any bit is
equal to 1 in an integer it will become TRUE but if no bits
are equal to 1 in the integer it will be a FALSE?
For historical reasons, there is an implicit conversion of all
arithmetic types to bool: if the value is equal zero (or the the
null pointer, for pointer types), it is converted to false;
otherwise to true.
This is really a legacy feature, and should generally be avoided
in modern code. (There is a tendancy to exploit them in
expressions using & and | because the precedence of these
operators is wrong. Thus:
if ( a & b != 0 )
does NOT do what you might expect; you generally need:
if ( (a & b) != 0 )
..)
The second statetment contained a typo, I'm sorry, it should
have read: SOMECODE||SOMEOTHERCODE but I think I understand
that one from your explanation for the "&" case.
Attention: && and || are very different from & and |. The
first are logical, connective and and or: the left operand is
converted to bool (if it isn't bool already); the right operand
is only evaluated if necessary. So things like:
if ( p != NULL && p->someValue != 0 )...
are guaranteed to not result in a null pointer access. The &
and | operators, on the other hand, are bitwise operators on
integral types; integral promotion is applied to both operands
(so an operand of type bool is converted to int), then the usual
arithmetic conversions are applied, and the resulting values are
or'ed or and'ed bit by bit. Note that this can (at least
theoretically) result in some surprises if negative values are
involved, since the representation of negative values varies (or
can vary); for this reason, some programmer (like myself) only
use them on unsigned integral types.
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34