When curly braces are optional

A syntax note: if the code that follows the conditional expression consists of only one statement, then the curly braces are optional. So the following code is equivalent to the previous example.

B​O​O​L​ ​i​s​N​o​t​L​e​g​a​l​ ​=​ ​!​(​(​t​r​u​c​k​W​e​i​g​h​t​ ​>​ ​0​.​0​)​ ​&​&​ ​(​t​r​u​c​k​W​e​i​g​h​t​ ​<​ ​ ​4​0​0​0​0​.​0​)​)​;​
i​f​ ​(​i​s​N​o​t​L​e​g​a​l​)​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​T​r​u​c​k​ ​w​e​i​g​h​t​ ​i​s​ ​n​o​t​ ​w​i​t​h​i​n​ ​l​e​g​a​l​ ​r​a​n​g​e​.​​n​"​)​;​

However, the curly braces are necessary if the code consists of more than one statement.

B​O​O​L​ ​i​s​N​o​t​L​e​g​a​l​ ​=​ ​!​(​(​t​r​u​c​k​W​e​i​g​h​t​ ​>​ ​0​.​0​)​ ​&​&​ ​(​t​r​u​c​k​W​e​i​g​h​t​ ​<​ ​ ​4​0​0​0​0​.​0​)​)​;​
i​f​ ​(​i​s​N​o​t​L​e​g​a​l​)​ ​{​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​T​r​u​c​k​ ​w​e​i​g​h​t​ ​i​s​ ​n​o​t​ ​w​i​t​h​i​n​ ​l​e​g​a​l​ ​r​a​n​g​e​.​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​I​m​p​o​u​n​d​ ​t​r​u​c​k​.​​n​"​)​;​
}​

Why? Imagine if you removed the curly braces.

B​O​O​L​ ​i​s​N​o​t​L​e​g​a​l​ ​=​ ​!​(​(​t​r​u​c​k​W​e​i​g​h​t​ ​>​ ​0​.​0​)​ ​&​&​ ​(​t​r​u​c​k​W​e​i​g​h​t​ ​<​ ​ ​4​0​0​0​0​.​0​)​)​;​
i​f​ ​(​i​s​N​o​t​L​e​g​a​l​)​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​T​r​u​c​k​ ​w​e​i​g​h​t​ ​i​s​ ​n​o​t​ ​w​i​t​h​i​n​ ​l​e​g​a​l​ ​r​a​n​g​e​.​​n​"​)​;​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​I​m​p​o​u​n​d​ ​t​r​u​c​k​.​​n​"​)​;​

This code would make you very unpopular with truck drivers. In this case, every truck gets impounded regardless of weight. When the compiler does not find a curly brace after the conditional, only the next statement is considered part of the if construct. Thus, the second statement is always executed. (What about the indention of the second statement? While indention is very helpful for human readers of code, it means nothing to the compiler.)

In this book, we will always include the curly braces.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset