News for hackers. Stuff that matters.
Re:‘Abusing’ the C switch statement – beauty is in the eye o... by saurik on Thursday February 02, 2017 @11:19AM (#13551651)
I think this looks a lot better if you use "if (false);" at the top to normalize the "else if" in the rest of the chain.

    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);
That said, I think the entire concept of this code having both the enum switch and the valid_* functions is just horrible :/.

To be clear, it isn't that I find the code difficult to grok: if you don't understand how switch works, please stop using C.

The issue is that this particular use case for the switch is a lazy performance optimization, as it should just totally replace the valid_* calls if we do that; it is like the author doesn'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't edit it? I just don't get it, particularly when any modern C compiler supports "give me a warning if I don't consume all the possible switch values in this enum", which is the feature that this code should be using, not if < END_*.

BTW: it isn'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.

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by yokohummer7 on Thursday February 02, 2017 @01:18PM (#13552953)
> To be clear, it isn't that I find the code difficult to grok: if you don't understand how switch works, please stop using C.

Oh please. C is perfectly usable without knowing switch is actually a bunch of gotos. The idea that one has to know all the hidden edges of a language to use it is pointless, because every language has something like that. Even Python can be a minefield if one tries hard abusing metaclasses, and I'm pretty sure 95% of the Python users don't know how to use them.

If you pursue the idea of knowing every deep place to the extreme, the only language left for general developers to use is Go. A language so concerned at removing hidden features that almost no features are left.

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by saurik on Thursday February 02, 2017 @02:37PM (#13553778)
Ok, I don't mean "stop writing C", but "stop reading C": people too often look at not-even-difficult things and say "I happen to not have bothered to learn that, so you shouldn't use it in writing, as I couldn't read it", which to me sounds exactly like someone saying "I happen to have a first grade reading level, so you shouldn't use big words or long sentences or prepositions, because I didn't understand them". There are times and places where that is appropriate, but those are not all times and places, not I would argue the majority of times and places.
Re:‘Abusing’ the C switch statement – beauty is in the eye o... by GFK_of_xmaspast on Friday February 03, 2017 @07:57AM (#13559451)
I've been doing c for almost 25 years now, and for many of those years it was my primary language, and not only would I refuse to write that kind of crazy switch construct I would refuse to allow it to pass code review.
Re:‘Abusing’ the C switch statement – beauty is in the eye o... by digler999 on Thursday February 02, 2017 @03:19PM (#13554240)
> The idea that one has to know all the hidden edges of a language

switch is hardly a hidden edge, it's an important control structure in the language. You want a "hidden edge", look at designated initializers [1] which I just heard of yesterday (thanks to HN), despite having 17 years experience using C. Or bitfields, or function pointers.

[1] http://www.drdobbs.com/the-new-c-declarations-initialization...

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by AnimalMuppet on Thursday February 02, 2017 @04:34PM (#13554885)
Switch is hardly a hidden edge, but using it like that is.
Re:‘Abusing’ the C switch statement – beauty is in the eye o... by tomjakubowski on Friday February 03, 2017 @08:16AM (#13559562)
Huh, I wouldn't think of function pointers as a hidden edge in the language, and I've only been seriously using C for about 4 years.

Is there some crazy consequence of using function pointers that I've been missing? Callbacks are pretty ubiquitous in C code bases, and the "hand coded vtable" pattern isn't too uncommon.

Maybe the lesson is that what language feature are the "hidden edges" depend on one's domain.

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by digler999 on Friday February 03, 2017 @09:57AM (#13560154)
I was being figurative. nothing's hidden in an ANSI standardized language. My point was you can go along way in C without ever needing function ptrs. Their syntax isn't exactly welcoming, either. Compared to switch, which OP had compared to a hidden corner, need switch a lot more frequently than you need function pointers.
Re:‘Abusing’ the C switch statement – beauty is in the eye o... by minitech on Thursday February 02, 2017 @07:23PM (#13556454)
Designated initializers aren’t “hidden” at all, just new (and not that new).
Re:‘Abusing’ the C switch statement – beauty is in the eye o... by ConceptJunkie on Thursday February 02, 2017 @05:28PM (#13555472)
I've always understood switch statements just fine.

However, after this article, I now understand them a little better.

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by sh_tinh_hair on Thursday February 02, 2017 @11:48PM (#13557761)
Exactly.
Re:‘Abusing’ the C switch statement – beauty is in the eye o... by mikeash on Thursday February 02, 2017 @01:51PM (#13553280)
I find it pretty hard to understand. I think they ultimately boil down to a logical OR of the `valid` and equality with the various constants, but it's pretty painful.

I'd never write something like this in code that might make it to production. The odds of the next guy misunderstanding it, or of me misunderstanding it in six months, are way too high. I'd only consider using it as part of an IOCCC entry.

(And to preempt any cries of "well, you just don't understand C very well," I do have a winning entry in the IOCCC.)

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by ggggtez on Thursday February 02, 2017 @01:14PM (#13552905)
Agreed. Without timing, the author just assumes it must be faster. However the valid_ function isn't even optimized. He seriously purposes

if(x) return true; else return false;

Why not just

return x;

It's clear the author is trying to optimize something, but they don't even start with the obvious places first.

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by pyre on Thursday February 02, 2017 @01:47PM (#13553232)
That really seems like the sort of thing that the compiler should be optimizing, the rest just being a case of coding style. It really seems (to me) like saying that `i += 1` isn't as "optimized" as `i++`.
Re:‘Abusing’ the C switch statement – beauty is in the eye o... by mikeash on Thursday February 02, 2017 @01:53PM (#13553320)
Yeah, if your compiler can't optimize the if statement to the same code as the direct return, throw it away and get a new one.

And there is pretty much never an "obvious" place to optimize. Profile first. If you want to call it "obvious" if something takes up 90% of the runtime in the profiler when it shouldn't, then that's acceptable, but don't just look at the code and say "obviously this part is slow."

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by krylon on Thursday February 02, 2017 @03:03PM (#13554051)
> if your compiler can't optimize the if statement to the same code as the direct return, throw it away and get a new one

To be fair, in embedded programming, you are sometimes stuck with the compiler a particular vendor hands you.

> And there is pretty much never an "obvious" place to optimize. Profile first.

Yes, a thousand times yes! ;-) I remember writing a rather convoluted piece of C code a couple of years back that involved stuffing data into a data structure, then looking up data in that data structure. My first thought was "I'm gonna need a hash table", but I used an array and qsort/bsearch, so I could get the rest working; when the rest was working (as in giving me correct results, but at glacial speed), I ran a profiler, fully expecting it to tell me the array/qsort/bsearch-thing was wasting huge amounts of time. I was rather surprised that it amounted to ~2% of the total running time. I've had people tell me before to profile, then optimize the parts that matter, and not to make any assumptions about what parts of my code are going to need optimization. And I did believe the people telling me this, but only at that moment did I understand how right those people were.

> "obviously this part is slow."

Telling whether a given piece of code is slow (in the sense of "this part could be optimized to run 10x as fast) or not is not too difficult, IMHO. Telling whether it makes up for a significant percentage of the total running time, is. Very hard.

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by mikeash on Thursday February 02, 2017 @03:12PM (#13554162)
Good point with embedded systems. I must have momentarily forgotten that there are targets beyond PC-like devices.
Re:‘Abusing’ the C switch statement – beauty is in the eye o... by dllthomas on Thursday February 02, 2017 @11:03PM (#13557575)
> And there is pretty much never an "obvious" place to optimize.

Never an obvious place to microoptimize. If you know you're doing a huge amount of unnecessary work, cutting that out can often be obvious.

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by ue_ on Thursday February 02, 2017 @11:53AM (#13551993)
>To be clear, it isn't that I find the code difficult to grok: if you don't understand how switch works, please stop using C.

As an aspiring C programmer, is there anywhere I can read about interesting applications of the switch statement? Pretty much everything I've learned has come with neat little break;s and default at the end of each case.

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by lentil_soup on Thursday February 02, 2017 @12:15PM (#13552216)
If you're an aspiring C programmer don't worry about these weird quirks. Don't believe that you need to know that to use C. A switch statement with "neat little breaks and default" is more than what you'll need 99% of the time.
Re:‘Abusing’ the C switch statement – beauty is in the eye o... by iainmerrick on Thursday February 02, 2017 @12:44PM (#13552575)
The remaining 1% is a big comment reading "/* FALL THROUGH */" instead of a break. Once you know what break does, you should know what happens when you leave it out (and why you might want to).

The remaining 0% is stuff like Duff's Device.

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by geofft on Thursday February 02, 2017 @12:40PM (#13552528)
A switch statement is just a bunch of gotos who have hurriedly put on an ill-fitting suit and tie to look respectable.

Any context where you would want "if x == this, goto here; if x == that, goto there" is a potential place to use the switch statement. Duff's device is a good example, but there are many things that can be built this way.

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by dllthomas on Thursday February 02, 2017 @11:06PM (#13557588)
> Any context where you would want "if x == this, goto here; if x == that, goto there" is a potential place to use the switch statement.

Only if "here" and "there" are later on in the same block.

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by pkkim on Thursday February 02, 2017 @11:56AM (#13552022)
Probably not for production use (as most "interesting" code isn't): https://en.m.wikipedia.org/wiki/Duff's_device
Re:‘Abusing’ the C switch statement – beauty is in the eye o... by ConceptJunkie on Thursday February 02, 2017 @05:32PM (#13555521)
You say that, but I pulled out several instances of Duff's Device from production code a few years ago, and replaced them with memcpy( ) and memcmp( ) as appropriate. This isn't 1986 any more.
Re:‘Abusing’ the C switch statement – beauty is in the eye o... by paulrpotts on Friday February 03, 2017 @10:28AM (#13560399)
If you want to read about horrible but entertaining C hacks, check out the entries in the International Obfuscated C Code Contest, the book that came out of the contests a few years back, or books like Deep C Secrets.

http://www.ioccc.org/

As an developer who has written a lot of shipping code in C and C++ for almost 30 years, I would strongly advise you to write your switch statements in as straightforward a way as possible. If you use fall through, place very noticeable /* FALL THROUGH */ comments to indicate that you meant to do that. If you wind up doing some kind of oddball thing because you _have confirmed_ that it results in significantly better optimization for a specific hardware target and compiler, comment the crap out of that, maybe make it conditional with an #if block, and (what I prefer to do is) write the simple version too, test both versions, and keep the simple version as a comment, so a future maintainer can verify that the complicated code is doing what you intended.

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by AnimalMuppet on Thursday February 02, 2017 @04:35PM (#13554897)
(Looks around...)

(Kisses karma goodbye...)

"Oh, give me a break!"

(Runs...)

Re:‘Abusing’ the C switch statement – beauty is in the eye o... by anoxic on Thursday February 02, 2017 @11:54AM (#13552000)
I think the idea is that when the interface changes, even if someone else comes in and makes some naive updates later, it should still continue running.