【问题标题】:C++ ignores if statementC++ 忽略 if 语句
【发布时间】:2015-11-27 07:12:02
【问题描述】:

有时 Visual C++ 会忽略 if 条件并且从不输入它! 在调试模式下,我看到条件表达式的值为真,但 C++ 忽略了它!

像这样:

if (childrens.at(j)->rules.size() > tempMax) {
    tempMax = childrens.at(j)->rules.size();
}

当我把它改成这个时它可以正常工作:

tempInt = childrens.at(j)->rules.size();
if (tempInt > tempMax) {
    tempMax = tempInt;
}

为什么,解决方法是什么?

【问题讨论】:

  • @ataman 这怎么可能有帮助?
  • 首先,你怎么知道条件为真?其次,你怎么知道 if 语句没有被执行?我愿意打赌你在这两个假设之一上是错误的。
  • 遗憾的是调试器并不总是正确的。因为调试器和编译器有非常不同的解释,所以我之前在 SO 上搞砸了自己。我不知道rules 是什么,但在标准库中的大多数类中,size() 返回一个无符号值。将其与 int 进行比较,您将度过一段糟糕的时光。将该无符号值填充到一个临时 int 中,测试该 int,您将得到一个非常不同的结果。我首先将警告提高到 MSVS 允许的最迂腐级别并进行重建。警告中可能有启示。
  • @user4581301 正在做某事。我的猜测是,tempMax 是否定的;也许您最初将其设置为 -1。与无符号值相比,它本身会被转换为无符号并回绕成一个非常大的数字。

标签: c++ visual-c++


【解决方案1】:

将此 else 添加到您的 if:

if (childrens.at(j)->rules.size() > tempMax) {
    tempMax = childrens.at(j)->rules.size();
}else{
    string inputCheck;
    cout<<"children."<<j<<".rules."<<childrens.at(j)->rules.size()<<" > "<<tempMax;
    cout<<"\nMy if - statement isn't working (Press Enter/Return to continue): ";
    cin.ignore(256,'\n');
    getline(cin,inputCheck);
}

看看你有什么。

【讨论】:

    【解决方案2】:

    @user4581301 告诉了问题,我检查了一下,他是对的。

    在这段代码中

    if (childrens.at(j)->rules.size() > tempMax) {
    tempMax = childrens.at(j)->rules.size();
    }
    

    rule.size() 返回无符号且温度 tempMaxint。它的初始值为 INT_MIN ,优化器忽略它,因为 unsigned int。总是大于负数,但是在输入 if body tempMax 后变为正数,我不知道为什么优化器会忽略它!

    我写了这个新程序

    int _tmain(int argc, _TCHAR* argv[])
    {
        
        vector<bool> a;
    
        for (size_t i = 0; i < 20; i++)
        {
            a.push_back(true);
        }
        
        int tempMax = INT_MIN;
    
        for (size_t i = 0; i < a.size(); i++)
        {
            if (a.size() > tempMax)
            {
                tempMax = a.size();
            }
        }
        
        cout << tempMax << endl;
        return 0;
    }
    

    输出是-2147483648

    在将 a.size() 的类型更改为 (int)a.size() 后,它已修复:

    int _tmain(int argc, _TCHAR* argv[])
    {
        
        vector<bool> a;
    
        for (size_t i = 0; i < 20; i++)
        {
            a.push_back(true);
        }
        
        int tempMax = INT_MIN;
    
        for (size_t i = 0; i < a.size(); i++)
        {
            if ((int)a.size() > tempMax)
            {
                tempMax = a.size();
            }
        }
        
        cout << tempMax << endl;
    
        return 0;
    }
    

    【讨论】:

    • 另外值得考虑的是size_t tempMax = 0; 并摆脱演员阵容。除非你需要一个完全没有向量的问题,否则永远不会少于 0 个元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 2015-08-13
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多