Patrick (patrickwonders) wrote,
Patrick
patrickwonders

C++ Quiz

So, I spent too much time today trying to figure out why this C++ code worked fine:

std::set::iterator found = m_transactionIDs.find(id);

if (found != m_transactionIDs.end())
{
    m_transactionIDs.erase(found);
}

if (someReallyComplexCondition)
{
    oneThing();
}
else if (someOtherComplexCondition)
{
    someOtherThing();
}

When changing it to this gave me a core dump with a stack trace of nothing but Ada:

std::set::iterator found = m_transactionIDs.find(id);

if (found != m_transactionIDs.end());
{
    m_transactionIDs.erase(found);

    if (someReallyComplexCondition)
    {
        oneThing();
    }
    else if (someOtherComplexCondition)
    {
        someOtherThing();
    }
}

I had temporarily thought of arranging the code like this:

std::set::iterator found = m_transactionIDs.find(id);
bool wasOurTransaction = (found != m_transactionIDs.end());

if (wasOurTransaction)
{
    m_transactionIDs.erase(found);
}

if (someReallyComplexCondition)
{
    oneThing();
}
else if (wasOurTransaction && someOtherComplexCondition)
{
    someOtherThing();
}

Then, I decided that I really didn't want the first condition to run if it wasn't our transaction either. In rearranging the code back so that the if-else block was nested in the found if, I ended up with a semi-colon after my if condition.

So... even when found equals m_transactionIDs.end(), I was trying to erase it.

Oi.

My bad.

Mostly.

I can see allowing empty bodies for while loops relying totally on side-effects of the condition to get anything useful done. And, for lots of for loops, it's the loop counter at the end that one's really calculating.

But, an if statement with an empty body? Why can't I at least get a warning from my compiler? I can see either of these cases as being legitimate:

if (condition)
    /* not-yet-implemented */;

if (condition)
{
#if SOMETHING_IS_BORKED_HERE
    abort();
#endif
}

But, if I wanted to write this:

if (condition);

Why did I bother to write the if at all?

I realize that after the C-preprocessor, something like this might be hard to distinguish:

#ifdef HAS_NOOP
#define NOOP() noop()
#else
#define NOOP()
#endif

if (condition)
   NOOP();

But, seriously, the pre-processor leaves whitespace and other cruft in there. I should at least be able to get a warning in the case where my semicolon is hiding against the condition's paren.

Or, is there some legitimate reason for this to be legitimate?

Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 4 comments