Wow, I’ve done 19 of these? Cool.
I got an email question from a reader earlier today, and I realized that his question would make a great “What’s wrong with this code” question.
He has a C++ function “GetValue” that is used to retrieve a value from something (it doesn’t actually matter what). His function is intended to be called from OLE automation, so it has three versions, one which takes a VARIANT, one which takes an integer index, one which takes a BSTR key. If the input VARIANT is an integer, it assumes that it’s an index, if the input VARIANT is a string, it assumes that it’s a key.
Here’s the version of the code as provided by the reader:
HRESULT GetValue(VARIANT Index, VARIANT& Value)
// Try Index as offset
HRESULT hr = VariantChangeType(&Index, &Index, 0, VT_I4);
return GetValue(Index.lVal, Value);
// Try Index as key
hr = VariantChangeType(&Index, &Index, 0, VT_BSTR);
return GetValue(Index.bstrVal, Value);
// Bad Index
His idea was that the function would be called like this:
Unfortunately, this doesn’t quite work :(. Why not?
As always Kudos and comments tomorrow.
Edit: I can’t count 🙂