c++ - 开关在 C++ 中不起作用

标签 c++ unicode c++11 switch-statement string-literals

我今天遇到了一个很奇怪的问题。让我们考虑以下代码:

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/

相关文章:

windows - 如何以跨平台友好的方式处理 C/C++ 中的 Unicode 字符串?

c++ - 如何在容器中指定模板化别名的泛型类型

c++ - 在 C++0x 中删除虚函数

c++ - Gedit 如何将其 api 暴露给 python 以供插件使用?

C++继承问题

c++ - 获取 Eigen C++ 库 Vector 的最大系数的位置

c++ - 更改类中的 vector 值时出错

html - 如何从动态列表的最后一个元素中删除 html unicode 内容?

linux - 在 C++ 中使用 Unicode (UTF-8)

c++ - 为什么即使成员函数是 constexpr 也需要 constexpr?