【问题标题】:How is my simple if-else statement unreachable code?我的简单 if-else 语句无法访问代码如何?
【发布时间】:2019-04-06 10:08:43
【问题描述】:

老实说,我收到一个错误感到震惊。我是一名初级 CS 专业的学生,​​我无法让这个简单的程序正常工作。 Clion 说这两行无法访问,但我的测试用例似乎有效。

代码:

#include <iostream>
#include <string>
using namespace std;

int main() {

    string s = "";
    while(s != "|") {
        int val1 = 0;
        int val2 = 0;
        cin >> val1;
        cin >> val2;
        if(val1 == val2) {
            cout << "the numbers are equal.\n";
        } else {
            cout << "the smaller value is: " << min(val1, val2) << '\n'; // Says these two 
            cout << "the larger value is: " << max(val1, val2) << '\n'; // lines are unreachable
        }
        cin >> s;
    }

    return 0;
}

测试用例:

3 3
the numbers are equal.
f
4 5
the smaller value is: 4
the larger value is: 5
|

Process finished with exit code 0

如果这段代码如此不可访问,那么我的程序怎么会到达呢?

【问题讨论】:

  • 对我来说似乎是 CLion 中的一个错误。
  • CLion 错了。
  • 好的,谢谢你,因为这是我质疑我的智慧的时刻之一,哈哈。
  • 似乎 CLion 的分析没有考虑非常量引用。您可以将输入语句替换为引用和通过引用的赋值,它会给出相同的结果。
  • 实际上,经过更多搜索,这看起来最相关,但仍未标记为已修复:youtrack.jetbrains.com/issue/CPP-13000

标签: c++ if-statement unreachable-statement


【解决方案1】:

CLion 可能有一些问题

这个引起了我的注意:

您检查字符串是否等于聊天数组,这可能会在运行时得到解决,但代码检查器不喜欢它。尝试使用:

char s;
while(s!='|') {...}

除此之外我不知道...

它可能没有预测到变量的变化,尝试使用 volatile 关键字?这可能会有所帮助...这仍然是一个错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多