Home
21.
What happens if I omit a break in a switch-case statement?

The break statement enables program execution to exit the switch construct. Without it, execution continues evaluating the following case statements.

22.
How do I exit an infinite loop?

Use break to exit any loop containing it. Using return exits the function module, too.

23.
My while loop looks like while(Integer). Does the while loop execute when Integer evaluates to -1?

Ideally a while expression should evaluate to a Boolean value true or false. false is zero. A condition that does not evaluate to zero is considered to evaluate to true. Because -1 is not zero, the while condition evaluates to true and the loop is executed. If you want the loop to be executed only for positive numbers, write an expression while(Integer>0). This rule is true for all conditional statements and loops.

24.
Is there an empty while loop equivalent of for(;;)?

No, while always needs an accompanying conditional expression.

25.
I changed a do…while(exp); to a while(exp); by copying and pasting. Should I anticipate any problems?

Yes, big ones! while(exp); is already a valid yet empty while loop due to the null statement (the semicolon) following the while, even if it is followed by a statement block. The statement block in question is executed once, but outside of the loop. Exercise caution when copying and pasting code.

26.
Why bother to indent code within statement blocks, nested ifs, and nested loops when it compiles even without indentation?

You indent not for sake of the compiler, but for the sake of other programmers (humans) who might need to read or understand your code.

27.
You can implement a quick fix using goto. Why would you still avoid it?

You avoid it to keep your code from getting unintuitive and expensive to maintain.

28.
Is it possible to write a for loop where the counter decrements? How would it look?

See the code in the solution to Exercise 1 that uses the decrement operator.

29.
What is the problem with the following loop?

for (int counter=0; counter==10; ++counter)
cout << counter << " ";

As the condition in the for statement is not satisfied, the loop won't execute even once and the cout statement it contains is never executed.

30.
What happens if I program a recursive function that doesn't end?

Program execution doesn't end. That might not be bad, per se, for there are while(true) and for(;;) loops that do the same; however, a recursive function call consumes more and more stack space, which is finite and runs out, eventually causing an application crash due to a stack overflow.