Topic: Result of bool v = true; v ^= 2;


Author: Manuel Menezes de Sequeira <Manuel.Sequeira@iscte.pt>
Date: 2000/02/02
Raw View
I was experimenting with assignement operators and boolean operators and
wrote the following code:

    #include <iostream>
    using namespace std;

    int main() {
        bool v = true;
        v ^= 2;
        cout << (v ? "true" : "false") << endl;
        bool w = true;
        w = w ^ bool(2);
        cout << (w ? "true" : "false") << endl;
    }

I compiled it both with egcs-1.1.2-12 (egcs-2.91.66) and VC++ 5.  In
both cases the result of execution was:
    true
    false

I thought it should have been:
    false
    false

According to 5.17 clause 3, the expression "2" in "v ^= 2;" is
"implicitly converted (clause 4) to the cv-unqualified type of the left
operand".  According to 4.7 clause 4, "if the destination type is bool,
see 4.12", which says, "an rvalue of [several types] can be converted to
an rvalue of type bool.  A zero value [...] is converted to false; any
other value is converted to true."  Hence, the expression "2" should be
converted to true.  According to 5.17 clause 7, "the behaviour of an
expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 except
that E1 is evaluated only once."  The result of "v ^= 2;" should then be
the same as obtained by the expression "v = v ^ bool(2);", i.e., "v = v
^ true", if I understood the standard right.  Acording to 5.12, operands
E1 and E2 should then undergo the usual arithmetic conversions in 5
clause 9, which states "[...] - otherwise, the integral promotions (4.5)
shall be performed on both operands."  According to 4.5 clause 4, "an
rvalue of type bool can be converted to an rvalue of type int, with
false becoming zero and true becoming one."  Hence, the result of "v ^
true" should be the same result of "1 ^ 1", i.e., zero.  Converted back
to bool, the result in "v" should be false.

I am assuming that the E2 in 5.17 clause 7 refers to the second operand
but after the implicit conversion mentioned in clause 3, though this is
not very clear in the text of the standard.

Manuel Menezes de Sequeira


---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]