Question

I just spent way too long trying to diagnose why, in the following snippet of code, the ProcessEvent() method seemed to be ignoring the false value I passed in for aInvokeEventHandler:

HRESULT 
CEventManager::
Process(Event anEvent)
{
    return (m_pPool->GetFsm()->ProcessEvent(anEvent), false);
}

// Definition of ProcessEvent()
HRESULT ProcessEvent(const Event& anEvent, bool aInvokeEventHandler = true);

Whenever I broke in the ProcessEvent() method, aInvokeEventHandler would always be true, regardless of whether I passed in false.

It took a workmate to point out to me that the false value should be inside the inner parentheses on the return line, like so:

return m_pPool->GetFsm()->ProcessEvent(anEvent, false); // Corrected code

As soon as I saw this, I kicked myself. Spotting this was obviously made harder because the original coder used redundant outer parentheses on the return line.

My question is, why didn't the compiler pick this up for me?

My method is returning a HRESULT, yet in the original code above, I am clearly returning a composite set of values in parentheses, i.e:

(HRESULT, bool)

Is notation like this acceptable in the C/C++ standards, and if so, what purpose would there be in allowing this? Or is this a bug in the compiler?

Was it helpful?

Solution

You are suffering from the comma operator, which evaluates and discards the value of its left-hand operand, and then evaluates its right-hand operand as the value of the expression.

Also, the default value for the argument to ProcessEvent is why your one-argument call was acceptable.

OTHER TIPS

What you wrote:

return (m_pPool->GetFsm()->ProcessEvent(anEvent), false);

What it means (roughly):

bool temp = false;
m_pPool->GetFsm()->ProcessEvent(anEvent);
return temp;

The comma is actually a valid operator - see this post.

The problem you are seeing lies in two things.

  1. The comma operator is throwing away the value on the left side and returning only the right side value (fasle)

  2. An HRESULT is just a long value, and therefore there is an implicit conversion of the value false to HRESULT, thus no compiler error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top