Thread: case statement
View Single Post
  #7 (permalink)  
Old August 18th, 2003, 11:15 PM
nikolai nikolai is offline
Friend of Wrox
Points: 2,570, Level: 21
Points: 2,570, Level: 21 Points: 2,570, Level: 21 Points: 2,570, Level: 21
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: San Diego, CA, USA
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Okay, I realized it would only take a minute to test, and I'm glad I did, because my hunch (#2 above) was correct.

In a switch statement, you're essentially taking the value in the switch parens and comparing whether it's == the expression in the case statement.

Therefore,

switch($foo) {
  case "A" || "B":
  {
     BLOCK_A;
  }
}

really means (at it's strictest)

if(($foo) == ("A" || "B"))
{
   BLOCK_A;
}

Or it might mean this (subtle difference, but dangerous!)
if($foo == "A" || "B")
{
   BLOCK_A;
}

In the first case, we are comparing a variable with "true". Since any non-boolean will be converted to a boolean for the comparison, only non-zero integers and non-empty strings will actually return false.

In the second case, we are comparing a variable with "A" and then ORing with "B". Since "B" is a string in a boolean context, it's converted to the boolean true. If either side of a boolean expression is true, then the entire expression is true, which means that case statement will always execute.

I didn't write a detailed enough test to figure out WHICH of the two possibilities is what's really happening, but this test demonstrates that it is, in fact, incorrect behavior none the less:

Code:
<?php

$foo = "D";

switch($foo)
{
    case "A" || "B":
    {
        echo 'case "A" || "B":' . "\n";
        break;
    }
    case "D":
    {
        echo 'case "D"' . "\n";
        break;
    }
}

?>
Take care,

Nik
http://www.bigaction.org/
Reply With Quote