‘Abusing’ the C switch statement – beauty is in the eye of the beholder
I think this looks a <i>lot</i> better if you use &quot;if (false);&quot; at the top to normalize the &quot;else if&quot; in the rest of the chain.<p><pre><code>    switch (x) default: if (false);
        else if (valid_command_message(x))
        case CMD1: case CMD2: case CMD3: case CMD4:
            process_command_msg(x);
        
        else if (valid_status_message(x))
        case STATUS1: case STATUS2: case STATUS3:
            process_status_msg(x);
        
        else
            report_error(x);
</code></pre>
That said, I think the entire concept of this code having both the enum switch and the valid_* functions is just horrible :&#x2F;.<p>To be clear, it isn&#x27;t that I find the code difficult to grok: if you don&#x27;t understand how switch works, please stop using C.<p>The issue is that this particular use case for the switch is a <i>lazy</i> performance optimization, as it should just totally replace the valid_* calls if we do that; it is like the author doesn&#x27;t want to update the switch cases, but wants the code to keep working? Did they just forget the switch exists, or is it that they can&#x27;t edit it? I just don&#x27;t get it, particularly when any modern C compiler supports &quot;give me a warning if I don&#x27;t consume all the possible switch values in this enum&quot;, which is the feature that this code should be using, not if &lt; END_*.<p>BTW: it isn&#x27;t clear to me that this would even be a performance optimization; in an ironic twist, many compilers are going to choose to compile that switch statement into the moral equivalent of two if statements with range checks, as default has to be implemented as a range check anyway, and if you work out how many range checks you are doing combined with the code cache benefits of having explicit branches instead of implicit jump tables, this switch statement is going to feel extra repetitive when you look at the machine code.