Deutsch   English   Français   Italiano  
<vstimp$mis5$1@dont-email.me>

View for Bookmarking (what is this?)
Look up another Usenet article

Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail
From: David Brown <david.brown@hesbynett.no>
Newsgroups: comp.lang.c
Subject: Re: enums and switch vs function calls
Date: Sun, 6 Apr 2025 11:49:13 +0200
Organization: A noiseless patient Spider
Lines: 50
Message-ID: <vstimp$mis5$1@dont-email.me>
References: <vsr0ml$1to9m$1@dont-email.me> <vsrjlk$2krsr$1@dont-email.me>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
Injection-Date: Sun, 06 Apr 2025 11:49:14 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="c834e100dafac4982983aaf86b8c8fc3";
	logging-data="740229"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX18+FV1IXJDf+YEa3tYANTDbdM8dlP7LIns="
User-Agent: Mozilla Thunderbird
Cancel-Lock: sha1:2nO2rXiWo1T8FjYwmehWU/Lr3XI=
In-Reply-To: <vsrjlk$2krsr$1@dont-email.me>
Content-Language: en-GB
Bytes: 2374

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.