Consider the following code:
#include <iostream>
using namespace std;
int main()
{
int x, y, i;
cin >> x >> y >> i;
switch(i) {
case 1:
// int r = x + y; -- OK
int r = 1; // Failed to Compile
cout << r;
break;
case 2:
r = x - y;
cout << r;
break;
};
}
G++ complains:
<source>: In function 'int main()': <source>:14:14: error: jump to case label 14 | case 2: | ^ <source>:11:17: note: crosses initialization of 'int r' 11 | int r = 1; // Failed to Compile | ^
My questions are:
- What is
crosses initialization? - Why do the first initializer
x + ypass the compilation, but the latter failed? - What are the problems of so-called
crosses initialization?
I know I should use brackets to specify the scope of r, but I want to know why, for example why non-POD could not be defined in a multi-case switch statement.
The version with
int r = x + y;won’t compile either.The problem is that it is possible for
rto come to scope without its initializer being executed. The code would compile fine if you removed the initializer completely (i.e. the line would readint r;).The best thing you can do is to limit the scope of the variable. That way you’ll satisfy both the compiler and the reader.
The Standard says (6.7/3):