Sujet : Re: enums and switch vs function calls
De : thiago.adams (at) *nospam* gmail.com (Thiago Adams)
Groupes : comp.lang.cDate : 05. Apr 2025, 16:53:24
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vsrjlk$2krsr$1@dont-email.me>
References : 1
User-Agent : Mozilla Thunderbird
Em 4/5/2025 7:29 AM, Richard Harnden escreveu:
If I have:
enum colour {RED, GREEN, BLUE}
int colour_to_hex(enum colour colour)
{
switch (colour)
{
RED: return 0xff0000;
GREEN: return 0x00ff00;
// BLUE: return 0x0000ff;
}
...
}
... then the compiler will warn me that I've missed a case in the switch statement. Which is good and very helpful.
But if I do:
int hex = colour_to_hex(10);
... then the compiler doesn't complain that 10 is not in the enum.
Why? Surely the compiler can tell.
Sometimes enums are used as bit set.
f(BIT1 | BIT2)
this situation would generate a lot of warning because BIT1|BIT2 is not part of the enum, just BIT1 and BIT2 separately.
One way that this could be fixed is adding an attribute
[[bitset]]
enum E{ BIT1 = 2, BIT2 = 4};
Then the compiler would not generate a warning in this case.