Re: enums and switch vs function calls

Liste des GroupesRevenir à cl c 
Sujet : Re: enums and switch vs function calls
De : david.brown (at) *nospam* hesbynett.no (David Brown)
Groupes : comp.lang.c
Date : 06. Apr 2025, 10:49:13
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vstimp$mis5$1@dont-email.me>
References : 1 2
User-Agent : Mozilla Thunderbird
On 05/04/2025 17:53, Thiago Adams wrote:
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.
 
gcc has the "flag_enum" attribute precisely for this purpose. Standardising it in the C standards would be nice, but the C standard does not currently have much that is merely about improving compiler warnings.

Date Sujet#  Auteur
5 Apr 25 * enums and switch vs function calls12Richard Harnden
5 Apr 25 +* Re: enums and switch vs function calls9Stefan Ram
5 Apr 25 i+- Re: enums and switch vs function calls1David Brown
5 Apr 25 i+- Re: enums and switch vs function calls1Stefan Ram
6 Apr 25 i`* Re: enums and switch vs function calls6Tim Rentsch
6 Apr 25 i +- Re: enums and switch vs function calls1David Brown
7 Apr 25 i +- Re: enums and switch vs function calls1Tim Rentsch
25 Apr 25 i `* Re: enums and switch vs function calls3Ben Bacarisse
25 Apr 25 i  `* Re: enums and switch vs function calls2Ben Bacarisse
4 May 25 i   `- Re: enums and switch vs function calls1Tim Rentsch
5 Apr 25 `* Re: enums and switch vs function calls2Thiago Adams
6 Apr 25  `- Re: enums and switch vs function calls1David Brown

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal