visual c++忽略if语句

visual C++ ignores if statement

本文关键字:语句 if 忽略 c++ visual      更新时间:2023-10-16

有时visualc++会忽略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;
}

为什么?修复方法是什么?

将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);
}

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

在这个代码中

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

rule.size()返回unsigned,且tempMaxint。它的初始值是INT_MIN,优化器忽略它,因为unsigned int。总是大于负,但进入后,如果身体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;
}