Converting switch-case to a single line statement

When writing a program, a simple switch case seems to take up a lot of space or for that matter any other decision making statement blocks. I would especially like to highlight the case of switch-case because in they end they generally turn out to be like this

switch(n){
 case 1:
  func1();
  break;
 case 2:
  func2();
  break;
 case 3:
  func3();
  break;
 default:
  func4();
}

A block like this is a bit tedious and lengthy, but the job it does is quite obvious. But what if we could convert all of this block into a single line statement using the ?: operator? Surely we all know the ternary operator and maybe, just maybe have used it a few times. But a nested ?: operator could really weave such a magic that we could actually compress all of this to a single line. For example, the above block of code would become

(n==1) ? func1() : (n==2) ? func2() : (n==3) ? func3() : func4();

And we have quite a distinct advantage when we use this kind of a statement:

  1. We are actually compressing many lines of the program into a single line.
  2. The flexibility of the ?: operator even allows us to use this with inequality, greater than or less than comparisons and even float values or any other expression that yields us boolean values rather than the equality test which we get in the switch-case statements.
  3. And we eliminate the break statements in every line!!

The nested ?: operator actually helped do all this. Surely this could be of use in obfuscated coding. But why didn’t I think of this before??

Advertisements

2 thoughts on “Converting switch-case to a single line statement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s