simple c++ question about switch and "cross-initialization" error?
1970-01-01 00:00:00 UTC
simple c++ question about switch and "cross-initialization" error?
Three answers:
2015-08-02 08:31:36 UTC
RE:
simple c++ question about switch and "cross-initialization" error?
switch (0) {
case 1:
int b = 0;
break;
default:
break;
}
This gives "error: jump to case label" and "error: cross initialization of 'int b.'" What does this mean?
Ways to remove error:
1) change line 3 into "int b; b = 0;"
2) put {} around...
Jazka
2010-03-29 02:51:13 UTC
I just moved the declaration for "b" outside the switch statement.
#include
using namespace std;
int main()
{
int b;
switch (0)
{
case 1:
b = 0;
break;
default:
break;
}
system ("PAUSE");
return 0;
}
?
2010-03-29 14:01:45 UTC
The reason is that such jump is a scoping violation. C++ standard ISO 14882:2003 says this in paragraph 6.7.3
It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps (77) 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).
77) The transfer from the condition of a switch statement to a case label is considered a jump in this respect.
so in your question, option (1) declares a POD variable without an initializer, which is expressly permitted, option (2) makes a new block, which ends its scope before the next case label, and thus you're no longer jumping into scope, and option (3) makes it impossible to jump into the block *after* the initialization because there are no case labels after default:.
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.