OK, so this little programming post is nothing like rocket science, it really isn’t. It is, however, REALLY useful, and something that almost nobody knows about the C language. We came across it when we were porting a game a few years ago, and none of us had ever seen it before. We tried it, and it works!
So, lets take a C switch statement
switch (somenumber) { case 1: case 2: case 3: do_something(); break; case 4: case 5: case 6: do_something else(); break; }
Fairly standard, nothing too unusual here. However there is another way to do it!
switch (somenumber) { case 1 ... 3: do_something(); break; case 4 ... 6: do_something else(); break; }
Unfortunately, it doesn’t seem to work on anything other than C/C++, which is a shame!
Enjoy!
That’s actually nice to know. Makes for easier-to-read code.
My personal favorite switch statement is Perl, though:
for ($variable){
if (/^abc$/){
do_something();
} elsif (/^[0-9]+$/){
do_something_else();
} else {
throw_an_error();
}
}
Ruby also allows this eg:
case number
when 1..4
do_something
when 5..10
do_something_else
when /[A-Za-z ]+/
do_something_alphabetic
else
do_something_defalt
end
WOW! I didnt know that i can do this in a switch statement .
It’s one of many GCC extensions to the C/C++ languages. It’s been there for a long time:
http://gcc.gnu.org/onlinedocs/gcc-4.3.3/gcc/C-Extensions.html#C-Extensions
Ah, so this is a GCC extension. A co-worker and I were absolutely amazed that we’d never heard of this before.
Do you mean that if i used it in a non-using GCC compiler, it won’t work?
Probably not. At least, I’ve never seen it in any book on standard C. Of course, there could be other compilers that also implement it as an extension.
Of course, you can still do some pretty strange things with switch in standard C. My favorite example (in the “I’m never, ever, EVER going to use that!” sense) is probably Duff’s Device: http://en.wikipedia.org/wiki/Duff%27s_device