Why I can't initialize a variable in switch case block
This question already has an answer here:
The case
statements in a switch()
have the same semantics as goto
: When you dispatch to a label in a switch
- case
, you effectively goto
the case
label. The reason for this is that cases in a switch
- case
aren't self-contained. You can fall-through from one case to another.
In fact, switch
- case
is so goto
-like that you can even write a monstrosity such as Duff's Device. Study that until you're properly horrified.
In C++, locally defined objects come into scope at their point of definition, and go out of scope at the closing curly brace of the enclosing scope. A break
or continue
statement that exits that scope is guaranteed to cleanly handle objects going out of scope.
For your switch
statement, the enclosing scope is defined by the curly-braces after switch()
.
Now, in C++, it's illegal to use goto
or something like it skip an object initialization. In your example, the case
and default
labels run afoul of that rule.
Your fix avoids the issue by replacing object initialization with object assignment. That's one way to fix it. Another is to add an additional level of scope:
case WM_LBUTTONDOWN:
{
HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 0));
break;
}
This works because the curly braces provide an extra level of scope clearly defining when hBrush
's lifetime ends.
In terms of technical detail: The statement that triggered the error relies on a copy constructor. The statement that did not relies on the copy assignment operator instead.
Retired Ninja: You can, you just need to enclose the block in {}
user3116182: yeah,I know that way
@user3116182: And why you're bothering about it??
Without scope declared variables, falling through case blocks will get into troubles to disambiguate them, or skipping variable initializations. That's all it's about.
链接地址: http://www.djcxy.com/p/14788.html上一篇: 在开关中声明变量?
下一篇: 为什么我无法在开关盒区块中初始化一个变量