71 lines
1.8 KiB
HTML
71 lines
1.8 KiB
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
|
|
|
|
<html>
|
|
<head>
|
|
<title>Switch statement</title>
|
|
<link href="style.css" rel="stylesheet" type="text/css">
|
|
</head>
|
|
<body background="images/back.gif">
|
|
<!--START-->
|
|
|
|
<h3>Switch statement</h3>
|
|
|
|
In a number of situations you want to let your action depend on a
|
|
particular value. You can do this using a number of if statements but it
|
|
is easier to use the switch statement. A switch statement has the
|
|
following form:
|
|
|
|
<p>
|
|
<blockquote>
|
|
<pre>
|
|
<b>switch</b> (<expression>)
|
|
{
|
|
<b>case</b> <expression1>: <statement1>; ... ; <b>break</b>;
|
|
<b>case</b> <expression2>: <statement2>; ... ; <b>break</b>;
|
|
...
|
|
<b>default</b>: <statement>; ...
|
|
}
|
|
</pre>
|
|
</blockquote>
|
|
|
|
<p>
|
|
This works as follows. First the expression is executed. Next it is
|
|
compared with the results of the different expressions after the case
|
|
statements. The execution continues after the first case statement with
|
|
the correct value, until a break statement is encountered. If no case
|
|
statement has the right value, execution is continued after the default
|
|
statement. (It is not required to have a default statement.)
|
|
Note that multiple case
|
|
statements can be placed for the same statement. Also, the break is not
|
|
required. If there is no break statement the execution simply continues
|
|
with the code for the next case statement.
|
|
|
|
<p>
|
|
<b>Example</b><br>
|
|
The following program takes action based on a key that is pressed.
|
|
|
|
<p>
|
|
<blockquote>
|
|
<pre>
|
|
<b>switch</b> (keyboard_key)
|
|
{
|
|
<b>case</b> vk_left:
|
|
<b>case</b> vk_numpad4:
|
|
x -= 4; <b>break</b>;
|
|
<b>case</b> vk_right:
|
|
<b>case</b> vk_numpad6:
|
|
x += 4; <b>break</b>;
|
|
}
|
|
</pre>
|
|
</blockquote>
|
|
|
|
|
|
<!--END-->
|
|
</body>
|
|
</html>
|
|
|
|
<!-- KEYWORDS
|
|
switch statement
|
|
case
|
|
break
|
|
--> |