C++ ignores if statement

时间:2015-09-01 22:36:56

标签: c++ visual-c++

Sometimes visual C++ ignores an if condition and never enters it! In debug mode I see the value of the conditional expression is true but C++ ignores it!

like this:

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

it works correctly when I change it to this :

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

Why, and what is the fix?

2 个答案:

答案 0 :(得分:0)

将此项添加到您的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);
}

看看你有什么。

答案 1 :(得分:0)

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

在此代码中

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

}

rule.size()返回unsigned和temp tempMax是int,它的初始值是INT_MIN,优化器忽略这个因为unsigned int总是大于负数,但是在输入之后如果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;
}
相关问题