Wertebereich einer Enumeration



  • Ich habe gerade gelesen, dass der Wertebereich einer Enumeration größer ist, als die Anzahl der Indizes. Stimmt das? Ist demnach folgendes erlaubt?

    enum Foo { x=-7, y }; // Wertebereich: -8 bis +7
    Foo f = static_cast<Foo>(5);
    


  • Gugelmoser schrieb:

    Ich habe gerade gelesen, dass der Wertebereich einer Enumeration größer ist, als die Anzahl der Indizes. Stimmt das? Ist demnach folgendes erlaubt?

    Ich verstehe so gar nicht, was Du meinst.

    Gugelmoser schrieb:

    enum Foo { x=-7, y }; // Wertebereich: -8 bis +7
    Foo f = static_cast<Foo>(5);
    

    Nein, das ist UB.


  • Mod

    Gugelmoser schrieb:

    Ich habe gerade gelesen, dass der Wertebereich einer Enumeration größer ist, als die Anzahl der Indizes. Stimmt das? Ist demnach folgendes erlaubt?

    enum Foo { x=-7, y }; // Wertebereich: -8 bis +7
    Foo f = static_cast<Foo>(5);
    

    Sofern dein Maschine 2er-Komplement benutzt, ist es -8 bis +7, sonst -7 bis +7; das ist also zulässig.
    Möglich ist sogar

    enum Foo { x=-7, y }; // Wertebereich: -8 bis +7
    Foo f = static_cast<Foo>(-10);
    

    Allerdings ist das Ergebnis dieser Umwandlung unspezifiert (und muss nicht einmal im Bereich -8 bis +7 liegen).



  • Tachyon schrieb:

    Ich verstehe so gar nicht, was Du meinst.

    I a nit.

    Laut Standard ist der underlying type int sofern nix anderes angegeben?



  • camper schrieb:

    Sofern dein Maschine 2er-Komplement benutzt, ist es -8 bis +7, sonst -7 bis +7; das ist also zulässig.

    Danke, das wollt ich wissen. 🙂

    Swordfish schrieb:

    Laut Standard ist der underlying type int sofern nix anderes angegeben?

    For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can
    represent all the enumerator values defined in the enumeration. If no integral type can represent all the
    enumerator values, the enumeration is ill-formed. It is implementation-defined which integral type is used
    as the underlying type except that the underlying type shall not be larger than int unless the value of an
    enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is
    as if the enumeration had a single enumerator with value 0.


Anmelden zum Antworten