如下写法会报错crosses initialization of ‘int r’
switch(i) {
case 1:
int r = 1; // Failed to Compile
cout << r;
break;
case 2:
cout << r;
break;
};
正确的写法应该是
switch(i)
{
case 1:
{
int r = 1;
cout << r;
}
break;
case 2:
{
int r = x - y;
cout << r;
}
break;
};
标准说明如下:
It is possible to transfer into a block, but not in a way that
bypasses declarations with initialization. A program that jumps from a
point where a local variable with automatic storage duration is not in
scope to a point where it is in scope is ill-formed unless the
variable has POD type (3.9) and is declared without an initializer
(8.5).
https://stackoverflow.com/questions/2392655/what-are-the-signs-of-crosses-initialization