false条件在while循环中评估true

时间:2015-05-24 06:09:05

标签: c++ debugging

我一直在调试这段简单的代码,而且我仍然没有理解为什么在评估为false的条件下输入循环。这是代码:

#include <iostream>

unsigned long count = 1; // we assume 2 has been found.
unsigned long primeArr[3] = {0};

bool primeArrCanDiv(unsigned long n){
    for(unsigned long i = 0; i<count; i++){
        if(n%primeArr[i] == 0) return true;
    }
    primeArr[count] = n;
    return false;
}


int main(){
    unsigned long j=3;
    primeArr[0]=2;
    while(count<3){
        if(!primeArrCanDiv(j)) count++;
        ++j;
    }
    std::cout<<primeArr[count-1];
    return 0;
}

关于代码,介绍了2个全局var count = 1和一个数组primeArr[3]。现在,以下部分应该运行直到计数达到3:

while(count<3){
        if(!primeArrCanDiv(j)) count++;
        ++j;
    }

但它的运行次数应该超过应有的2倍,即使count = 3,也应该使3<3评估为假,对吧?但是当计数达到4时它就会停止。

添加std::cout<<primeArr[count-1];将打印7而不是5。

我已经尝试在nemiver中调试它,它显示条件被评估为false并且仍然进入循环。我知道我可能会留下一些愚蠢的想法,但仍想知道导致这种情况的原因。

屏幕截图:

enter image description here

在x64 arch linux上使用精确:g++ -g q7.cpp -o a.out和gcc -v gcc version 5.1.0 (GCC)

2 个答案:

答案 0 :(得分:1)

我刚刚在Visual Studio 2013中编译并执行了您的代码

#include <iostream>

unsigned long count = 1; // we assume 2 has been found.
unsigned long primeArr[3] = { 0 };

bool primeArrCanDiv(unsigned long n){
    for (unsigned long i = 0; i<count; i++){
        if (n%primeArr[i] == 0) return true;
    }
    primeArr[count] = n;
    return false;
}


int main(){
    unsigned long j = 3;
    primeArr[0] = 2;
    while (count<3){
        if (!primeArrCanDiv(j)) count++;
        ++j;
        std::cout << "foo" << std::endl;
    }
    return 0;
}

输出:

foo
foo
foo

您的代码似乎按预期工作。也许你的工具集是问题?

答案 1 :(得分:1)

The OP asked me to make my comment into an answer. Here goes.

You should avoid inlining statements and conditionals together. Always put the action on a seperate line from the "if" clause. For example:

if(!primeArrCanDiv(j)) count++;

Move the count++; statement to the next line and indented. Bonus points if you add curly braces.

This is much better C/C++ style:

if(!primeArrCanDiv(j))
{
    count++;
}

This makes the code both easier to read and to debug. Keeping the conditional expression and the subsequent statement on the same line might confuse some visual debuggers to show odd results. It definitely makes it easier for the person stepping through the code with the debugger to see which statements are actually executed.