Danger in using switch

One more caveat in using switch-statement is when you tend to use it like if-statement. Here is an example:

switch ($president) {
  case "Putin" || "Medvedev":
    $next_president = ($president == "Putin") ? "Medvedev" : "Putin";
  break;
  case "Stalin":
    $next_president = "Stalin";
    break;
}

Now. If you run this code you’ll get following results:
1. $president = ”; // $next_president = NULL
2. $president = ‘Obama’; // $next_president = “Putin”
3. $president = ‘Stalin’; // $next_president = “Putin”

What happened?

Here is what compiler does to this code.
Line3: "Putin" || "Medvedev" is converted to TRUE || TRUE and then shortened to TRUE. So we get:

 

switch ($president) {
  case TRUE:
    $next_president = ($president == "Putin") ? "Medvedev" : "Putin";
  break;
  case "Stalin":
    $next_president = "Stalin";
    break;
}

Now whenever string $president is compared with boolean TRUE it is also converted to boolean. So any non-empty string will match the first case statement and the line 5 will never be reached.
The correct way to use or-s is:

switch ($president) {
  case "Putin": 
  case "Medvedev": 
    $next_president = ($president == "Putin") ? "Medvedev" : "Putin";
  break;
  case "Stalin":
    $next_president = "Stalin";
    break;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.