(bool) true immer 1 ?



  • hola leute

    ist es im c++-std so festgelegt das true immer 1 ist ?

    dann koennte man eine bool variable durch ne subtraktion mit 1 jeder zeit in den anderen zustand bringen ohne zu wissen welchen er grad hat. oder ?

    bool var = true;
    var - 1 == 0; also false;
    var - 1 == -1; wird intern geaendert nach 1, und somit wieder true.

    oder ist das nicht so die optimale loesung ?

    Meep Meep



  • "An rvalue of arithmetic, enumeration, pointer, or pointer to member
    type can be converted to an rvalue of type bool. A zero value, null
    pointer value, or null member pointer value is converted to false; any
    other value is converted to true."



  • Eigentlich geht es ja mehr hierum:

    4.5 Integral promotions [conv.prom]

    1 An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int.

    2 An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) can be converted to an rvalue of the first of the following types that can represent all the values of its underlying type: int, unsigned int, long, or unsigned long.

    3 An rvalue for an integral bitfield (9.6) can be converted to an rvalue of type int if int can represent all the values of the bitfield; otherwise, it can be converted to unsigned int if unsigned int can represent all the values of the bitfield. If the bitfield is larger yet, no integral promotion applies to it. If the bitfield has an enumerated type, it is treated as any other value of that type for promotion purposes.

    4 An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.

    5 These conversions are called integral promotions.

    EDIT:

    Den Zustand eines bools kann man auch einfacher ändern:

    int main(void)
    {
        bool test; //Nicht initialisiert, eigentlich undefined behaviour, normalerweise ist aber einfach der Wert "zufällig"
        test = !test;
        return (0);
    }
    


  • waer ich mal blos regestriert ^^...

    @topic
    "If the destination type is bool, see _conv.bool_. If the source type
    is bool, the value false is converted to zero and the value true is
    converted to one."

    hoffentlich jetzt ein richtiges zitat 😑

    3.9.1 4.5.4 4.11

    dachte eigendlich immer aritmetik mit bool typen sei undefiniert...



  • Wenn du nen bool von true nach false ändern willst oder umgekehrt, dann nimm entweder meinbool = !meinbool wie von Phoemuex vorgeschlagen, oder meinbool = meinbool ^ true (kurz meinbool ^= true).
    Was einfacher zu lesen ist ist ansichtssache.



  • ^ ist aber ein bitweiser Operator, also der Situation nicht wirklich angmessen. Am besten nimmt man den logischen Negationsoperator (!), denn genau für sowas ist er ja da.


Anmelden zum Antworten