25.12.2015 Views

Professional

1l6xhbR

1l6xhbR

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Using blocks to group statements<br />

Notice that the syntax of the if statement shown earlier specifies a single statement after the<br />

if (booleanExpression) and a single statement after the else keyword. Sometimes, you’ll want to<br />

perform more than one statement when a Boolean expression is true. You could group the statements<br />

inside a new method and then call the new method, but a simpler solution is to group the<br />

statements inside a block. A block is simply a sequence of statements grouped between an opening<br />

brace and a closing brace.<br />

In the following example, two statements that reset the seconds variable to 0 and increment the<br />

minutes variable are grouped inside a block, and the entire block executes if the value of seconds is<br />

equal to 59:<br />

int seconds = 0;<br />

int minutes = 0;<br />

...<br />

if (seconds == 59)<br />

{<br />

seconds = 0;<br />

minutes++;<br />

}<br />

else<br />

{<br />

seconds++;<br />

}<br />

Important If you omit the braces, the C# compiler associates only the first statement<br />

(seconds = 0;) with the if statement. The subsequent statement (minutes++;) will not be<br />

recognized by the compiler as part of the if statement when the program is compiled.<br />

Furthermore, when the compiler reaches the else keyword, it will not associate it with the<br />

previous if statement; instead, it will report a syntax error. Therefore, it is good practice to<br />

always define the statements for each branch of an if statement within a block, even if a<br />

block consists of only a single statement. It might save you some grief later if you want to<br />

add additional code.<br />

A block also starts a new scope. You can define variables inside a block, but they will disappear at<br />

the end of the block. The following code fragment illustrates this point:<br />

if (...)<br />

{<br />

int myVar = 0;<br />

... // myVar can be used here<br />

} // myVar disappears here<br />

else<br />

{<br />

// myVar cannot be used here<br />

...<br />

}<br />

// myVar cannot be used here<br />

CHAPTER 4 Using decision statements 93

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!