原因是因为C和C++中,一个变量的生命期(作用域)是这么规定的,中文还不好解释,英文原文是这样的:The scope of a variable extends from the point where it is defined to the first closing brace that matches the closest opening brace before before the variable was defined.

原文http://zhubangbing.blog.163.com/blog/static/5260927020109821055992/,

上面的代码中这样写,在case 0x02中temp仍然有效,看看编译器提示的信息 cross initialization of int temp, 什么意思呢, 就是说跳过了变量的初始化,仔细想想,确实是这样,我们在case 1中定义了变量temp,在这个程序中,直到遇到switch的“}”右花括号,temp的作用域才终结,也就是说 在case 2 和 default 分支中 变量temp依然是可以访问的。考虑这样一种情况,如果switch匹配了case 2,这样case 1的代码被跳过了,那么temp就没有定义,如果此时在case 2的代码中访问了temp,程序会崩溃的。