You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带返回值的无限循环被优化致错误结果的标准依据及规避方法

C++优化引发的未定义行为疑问

我发现以下代码在MSVC和Clang开启优化编译时会输出“res = 0”,未开启优化则会如预期挂起。

#include <array>
#include <cstring>
#include <iostream>
#include <string>

const char* type_to_text(std::size_t type)
{
    return std::array{
        "one",
        "two",
        "three",
        ""
    } [(int)type];
}

std::size_t text_to_type(const char* name) {
    std::size_t type = 0;
    const char* name_of_type = nullptr;

    do {
        name_of_type = type_to_text(type);
        if (strcmp(name_of_type, name) == 0) {
            return type;
        }
        
        // ++type; // <- 该行被遗漏

    } while (strlen(name_of_type) > 0);

    return ((std::size_t)-1);
}

int main()
{
    std::string name("two");

    auto res = text_to_type(name.c_str());
    std::cout << "res = " << res << '\n';
}

我知道这是程序员的失误,也清楚未定义行为的概念,但有几个问题需要明确:

  • C++标准中哪一部分允许编译器做出这种返回“大概率错误”结果的优化?
  • 返回值难道不应该被视为优化后代码的副作用吗?
  • 除了常规的代码检查方法外,还有什么最佳实践可以规避这类问题?

另外我也质疑这种优化决策的合理性——在大型项目中,这种返回错误结果的情况比直接挂起的代码更难调试。

内容的提问来源于stack exchange,提问作者Damir Tenishev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 14:52:07