Changes

The Objective-C switch Statement

1,253 bytes added, 19:22, 12 October 2009
A switch Statement Example
}
</pre>
 
== Explaining the Example ==
 
When compiled and run, the sample application will prompt for a number between 0 and 5. Once entered, the response is assigned to the integer variable ''value'' which in turn is used as the ''governing variable'' in the ''switch'' statement.
 
The ''default'' option simply displays an out of range message if none of the case statements match the number entered by the user.
 
== Combining case Statements ==
 
In the above example, each case had its own set of statements to execute. Something a number of different matches will require the same code to be executed. In this case, it is possible to group case statements together with a common set of statements to be executed when a match for any of the cases is found. For example, we can modify the switch construct in our example so that the same code is executed regardless of whether the user enters 0, 1 or 2:
 
<pre>
switch (value)
{
case 0:
case 1:
case 2:
NSLog (@"zero, one or two");
break;
case 3:
NSLog (@"three");
break;
case 4:
NSLog (@"four");
break;
case 5:
NSLog (@"five");
default:
NSLog (@"Integer out of range");
break;
}
</pre>