A little-known trick with C switches

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!

  • Share/Bookmark

Tags: ,

7 Responses to “A little-known trick with C switches”

  1. blindcoder says:

    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();
    }
    }

  2. Clive Crous says:

    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

  3. Ahmed Ibrahim says:

    WOW! I didnt know that i can do this in a switch statement .

Leave a Reply

To stop spam, please answer this simple question
What OS do we make games for

Please note: This site is fully moderated