|
|
|
|
|
|
|
This code segment always prints out |
|
|
|
|
|
|
|
|
no matter what was input for n. Here is the reason. |
|
|
|
|
|
|
|
|
We've used the wrong operator in the If test. The expression n = 3 is not a logical expression; it's called an assignment expression. (If an assignment is written as a separate statement ending with a semicolon, it's an assignment statement.) An assignment expression has a value (above, it's 3) and a side effect (storing 3 into n). In the If statement of our example, the computer finds the value of the tested expression to be 3. Because 3 is a nonzero (TRUE) value, the then-clause is executed, no matter what the value of n is. Worse yet, the side effect of the assignment expression is to store 3 into n, destroying what was there. |
|
|
|
|
|
|
|
|
Our intention is not to focus on assignment expressions; we discuss their use later in the book. What's important now is that you see the effect of using = when you meant to use ==. The program compiles correctly but runs incorrectly. When debugging a faulty program, always look at your If statements to see whether you've made this particular mistake. |
|
|
|
|
|
|
|
|
There are no restrictions on what the statements in an If can be. Therefore, an If within an If is okay. In fact, an If within an If within an If is legal. The only limitation here is that people cannot follow a structure that is too involved. And readability is one of the marks of a good program. |
|
|
|
|
|
|
|
|
When we place an If within an If, we are creating a nested control structure. Control structures nest much like mixing bowls do, smaller ones tucked inside larger ones. Here's an example, written in pseudocode: |
|
|
|
|
|