Sunday 27 November 2011

switch cases' and variables

Whilst writing up a switch statement, it appeared that you cant use variables (arrays in this case) as a case statement.

for example int $mode=0 ; string $currentNum="One" ; string $array[]={"One","Two","Three"} ; if($mode==1) $array={"Three","Two","One"} ; switch($currentNum) { case $array[0]: print ("Next in array is "+$array[1]) ; break ; case $array[1]: print ("Next in array is "+$array[2]) ; break ; case $array[2]: print ("Next in array is "+$array[0]) ; break ; } However swapping the case $array[...] with a value like so... int $mode=0 ; string $currentNum="One" ; string $array[]={"One","Two","Three"} ; if($mode==1) $array={"Three","Two","One"} ; switch($currentNum) { case "One": print ("Next in array is "+$array[1]) ; break ; case "Two": print ("Next in array is "+$array[2]) ; break ; case "Three": print ("Next in array is "+$array[0]) ; break ; } Works just fine, which ended me using the old 'else if' instead. I haven't found anything that seems to mention this, and I know there are probably better ways anyway but it did stump me for a while.

No comments:

Post a Comment