Switch

From Sputnik Wiki
(Difference between revisions)
Jump to: navigation, search
(Example)
Line 55: Line 55:
 
     Case 2:
 
     Case 2:
 
{
 
{
        println("Value is 1 or 2");
+
            println("Value is 1 or 2");
 
}
 
}
 
break;
 
break;
 
     Case 3:
 
     Case 3:
 
{
 
{
        println("Value is 3");
+
            println("Value is 3");
 
}
 
}
 
break;
 
break;
 
     Case "test":
 
     Case "test":
 
{
 
{
        println("Value is \"test\"");
+
            println("Value is \"test\"");
 
}
 
}
 
break;
 
break;
 
     Default:
 
     Default:
 
{
 
{
        println("No preceding case was true!");
+
            println("No preceding case was true!");
 
}
 
}
 
}
 
}

Revision as of 16:40, 18 November 2011

Contents

Select...Case...Default

Description

Conditionally run statements.

Switch ( <expression> )
{
    Case <expression>
    {
        statement1
        ...
    }
    Case <expression>
    {
        statement2
        ...
    }
    Default
    {
        statementN
        ...
    }
}

Parameters

Switch <expression>

Any vaid expression to used and compared with the Case <expressions>

Case <expression>

If the expression matches the Switch <expression> the following statements up to the next Case or Default are executed. If more than one of the Case statements are true, only the first one is executed.

Note - If a Case is lacking a Break then the code will fall through into the next case and execute that and fall through again if theres no break.

Remarks

Switch statements may be nested.

Strings are case sensitive when used in a case.

Example

Heres an example with all breaks in proper place (Break statement is needed to tell the code to stop or else it wil fall through into the next case that may be what you want though)

$var = 1;
Switch ( $var )
{
    Case 1:
    Case 2:
	{
            println("Value is 1 or 2");
	}
	break;
    Case 3:
	{
            println("Value is 3");
	}
	break;
    Case "test":
	{
            println("Value is \"test\"");
	}
	break;
    Default:
	{
            println("No preceding case was true!");
	}
}

In the above example: if $var is 1 it will go into Case 1 then fall through into case 2 run the code and break if $var is 2 it will go into Case 2 run the code and break if $var is 3 it will go into Case 3 run the code and break if $var is "test" it will go into Case "test" run the code and break if $var does not match any case at all the code inside Default will be run

This means you can in theory place loads of empty Case statements that you want to all fall through.

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox