28 ms·
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);
by saurik 10y ago
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.
- ue_ 10y ago>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.
- pkkim 10y agoProbably not for production use (as most "interesting" code isn't): https://en.m.wikipedia.org/wiki/Duff's_device https://en.m.wikipedia.org/wiki/Duff's_device
- ConceptJunkie 10y agoYou 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.
- lentil_soup 10y agoIf 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.
- iainmerrick 10y agoThe 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.
- geofft 10y agoA 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.
- dllthomas 10y ago> 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.
- paulrpotts 10y agoIf 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/ 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.
- anoxic 10y agoI 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.
- ggggtez 10y agoAgreed. 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.
- pyre 10y agoThat 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++`.
- mikeash 10y agoYeah, 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."
- krylon 10y ago> 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.
- mikeash 10y agoI 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.)
- yokohummer7 10y ago> 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.
- saurik 10y agoOk, 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.
- deleted 10y ago[deleted]
- GFK_of_xmaspast 10y agoI'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.
- digler999 10y ago> 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-initializations/184401377 http://www.drdobbs.com/the-new-c-declarations-initialization...
- AnimalMuppet 10y ago(Looks around...) (Kisses karma goodbye...) "Oh, give me a break!" (Runs...)