pp 136 - 137: declaring variable in the switch statement ...
This question (or rather a comment perhaps) is about the remark that the author makes about enclosing curly braces and thus creating a block to make sure error C2360 does not appear, when defining a variable inside the case label of a switch statement. I will reproduce the text here to obviate the need for looking up in the book:
---
pp 136, last paragraph:
"The statements to be executed for a particular case can also be between braces, and sometimes this is necessary. For example, if you create a variable within a case statement, you must include braces. ..."
Then there is code example without braces - what the text fails to mention here is that this error is actually encountered at the compile time. Without the braces the program just does not compile.
I am, however, not very happy with the explanation:
"Because it is possible that the count variable may not get initialized within the block for the switch, you get the following error..."
Q. How does adding braces around the block to be executed for Case 1: actually help the cause, if above is the explanation? This looks more like a compiler syntax requirement - which tries to enforce good programming style and avoid unintended consequences. By adding the braces we make the count a local variable to that block and thus restrict the possibility that it could accidentally be accessed outside this block (and get an un-initialized garbage value). In any case, would have liked a bit clearer explanation - given the fact that each and every statement in the code is described in great detail in the text - which is good for the most part.
Perhaps author means the same thing but I wish this was stated more explicitly. Plus, this is my interpretation - I would like to confirm with others. Thanks much.
|