我今天遇到了一个很奇怪的问题。让我们考虑以下代码:
int llex(){
cout<<"enter 1"<<endl;
char32_t c = U'(';
cout<<(c==U'#')<<endl;
switch(c){
case U'#':
cout<<"enter 2"<<endl;
return 5;
default:
break;
}
}
int main( int argc, char** argv)
{
cout<<"enter 1"<<endl;
char32_t c = U'(';
cout<<(c==U'#')<<endl;
switch(c){
case U'#':
cout<<"enter 2"<<endl;
return 5;
default:
break;
}
cout << "------------" << endl;
llex();
}
输出是:
enter 1
0
------------
enter 1
0
enter 2
请注意 main 中的代码与 llex
函数中的代码相同。为什么他们输出不同的结果? (我在 clang 上使用 C++11)。
最佳答案
您的 llex()
函数应该总是返回一个值,但实际上并没有。如果控制流没有命中 return
语句,这就是未定义的行为。根据 C++11 标准的第 6.6.3/2 段:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
除非你解决这个问题,否则你不能对你的程序做出任何假设,也不能对它抱有期望。
例如,我无法重现 this fixed live example 中的行为.
关于c++ - 开关在 C++ 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16237650/