Code Blocks ({})In the previous if statement examples, only one statement follows if and else, a single System.Console.WriteLine(), similar to Listing 3.23. Listing 3.23. if Statement with No Code Block
However, sometimes you might need to execute multiple statements. Take, for example, the highlighted code block in the radius calculation in Listing 3.24. Listing 3.24. if Statement Followed by a Code Block
Output 3.14 shows the results of Listing 3.24. Output 3.14.
In this example, the if statement checks whether the radius is positive. If so, the area of the circle is calculated and displayed; otherwise, an invalid radius message is displayed. Notice that in this example, two statements follow the first if. However, these two statements appear within curly braces. The curly braces combine the statements into a single unit called a code block. If you omit the curly braces that create a code block in Listing 3.24, only the statement immediately following the Boolean expression executes conditionally. Subsequent statements will execute regardless of the if statement's Boolean expression. The invalid code is shown in Listing 3.25. Listing 3.25. Relying on Indentation, Resulting in Invalid Code
In C#, indentation is for code readability only. The compiler ignores it, and therefore, the previous code is semantically equivalent to Listing 3.26. Listing 3.26. Semantically Equivalent to Listing 3.25
Programmers should take great care to avoid subtle bugs like this, perhaps even going so far as to always include a code block after a control flow statement, even if there is only one statement.
|