开发者

Why does a false statement still execute?

I have this code...

void drawMap(void)
{
    if (false)
        return;

    for(auto iter = this->m_layers.begin(); iter !=开发者_C百科 m_layers.end(); ++iter)
    {
        if ((*iter)->get() == NULL)
            continue;
        PN::draw((*iter)->get(), b2Vec2(0,0), true, 0);
    }
}

If I'm not mistaken it should NEVER execute...but it does...and when I change

    if (false)
      return;

to

    if (false)
       return;
    else
       return;

it doesn't execute at all now, but how can that first statement NOT be false? grabs headache pills

P.S. I only did this 'cause I was debugging and noticed my code was drawing to the screen when it wasn't supposed to.


if (false) will never execute its body... because the value of the condition is never true. So in the code you've given, the remainder of drawMap will always execute because it will never return at the start.

Consider if (x == 5) - that will only execute if the expression x == 5 is true. Now substitute false for x == 5...

If you want an if statement which will always execute, you want

if (true)

instead.


Count me in with the crowd that didn't actually read the problem well enough, or couldn't believe that the OP didn't understand the problem if it were so simple :)

John Skeet's answer, of course, was spot on :)

Two thoughts:

  1. If you're in a debugger, lines can appear to be executed, out of order, not at all or at unexpected lines when compiled with optimizations. This is because some machine instructions will get 'attributed' to different source lines. Compile without optimization to eliminate the source of confusion. It is confusing only, as optimizations should (! barring compiler bugs) not alter effective behaviour

  2. It could be that you're getting an evil #define for false that you cannot trust. Rule this out by running the code through preprocessor only. g++ -E will do that. MSVC++ has an option to 'keep preprocessed' source

Blockquote


if (false)

is analagous to

if (1 == 2)

and will therefore never execute the next statement (or block).

In your context consider the following comments I made:

void drawMap(void)
{
    if (false) return; //Not gonna happen.

    //The following will always happen
    for(auto iter = this->m_layers.begin(); iter != m_layers.end(); ++iter)
    {
        if ((*iter)->get() == NULL)
            continue;
        PN::draw((*iter)->get(), b2Vec2(0,0), true, 0);
    }
}


I have seen the usage of this if(false), in a switch / case like construction like this:

int ret = doSomeThingFunction();
if (false) {}
else if (ret < 0 ) {

}
else if (ret == 0) {

}
else if (ret > 0) {

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜