Topic: bool conversions


Author: Steve Clamage <stephen.clamage@Eng.Sun.COM>
Date: 1997/09/02
Raw View
Mark Ehmry wrote:
>
> Given the following declarations/initializations:
>    int i = 4;
>    bool b;   // b is uninitialized (could be true or false).
>    b = i;    // after this assignment, b is true (1).
>
> What will be the results of each operation?
>    1.  b < i;
>    2a. b == i;  (I assume i==b is same result.)
>    2b. i == true;
>    3.  i & b;
>    4.  b && i;
>    5.  b + b + b;
>
> If I've interpreted the spec correctly, I think the results would be:
> 1.  true.  (relational expr., bool b gets promoted to an int)
> 2a. both false. (equality expr., b gets promoted to an int)
> 2b. false. (equivalent to 2a.)

Correct.

> [So consequently, the following 2 stmts. are not functionally
> equivalent:
>       if ( i == true ) ...
>       if ( i ) ...
> One would have to be careful in the semantics, "If i is true, then..." ]

Yes, but that is no change from the old semantics.

If 'i' has an arithmetic (but non-boolean) type, it was always
possible for (i!=true) and (i!=false) both to be true, for any common
implementation of a pseudo-boolean type. Introducing a true
boolean type has not changed that. You could always write
(bool(i)==true) (before or now) to get the desired effect.

In addition "if(i)" previously had the meaning "if(i!=0)". The
new meaning "if(bool(i))" gives the same results.

> 3.  int 0. (b gets promoted to an int, for a bitwise operation)
> 4.  true.  (here, int i gets converted to bool, for a logical op.)
> 5.  int 3. (arithmetic operators force bools to promote to ints)
>
> Are my interpretations correct?

Yes.

--
Steve Clamage, stephen.clamage@eng.sun.com
---
[ comp.std.c++ is moderated.  To submit articles: Try just posting with your
                newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu
]