Question on undefined behaviour
----------------------------
Please note:
Before I get the book thrown at me, let me state that I openly admit I am
not an expert on the C++ standard. I'm not even a novice!
It seems every time someone says something here, eventually somebody else
comes back with one of these:
"Listen, if you'd just simply read the standard you'd know from ISO/C99
++2003 2.5.1[a.32], 8.6.5.1[1.65] that you're completely wrong!"
I wish I had the time to sit down and read every last detail about the
language but I don't.
----------------------------
That being said, I have a technical question and a conditional question
depending on the answer.
Q1.
Suppose we had a function that took as an argument a buffer (reference or
pointer) and returned a boolean value indicating whether or not the buffer
was successfully filled with the requested data. Something like:
bool ReadRegistryDword(const char* strKeyName, DWORD& dwKeyValue);
or
bool ReadRegistryDword(const char* strKeyName, DWORD* pdwKeyValue);
I assume these are essentially equivalent except that the latter might
concievably be passed NULL for the value part.
----
Then, is it not true that the following sequence is undefined?
DWORD dwKeyValue;
if(ReadRegistryDword("SomeKeyName", dwKeyValue) && dwKeyValue != 0)
{
puts("Key value non zero");
}
My guess is that the answer is YES. Undefined behaviour (similar to var =
++var + var).
-------------------------
If A1 == YES then the follow-up question is this:
Q2:
Shouldn't it be considered bad practice to define a function which takes as
input an "__out" value and returns anything that can be used in a
conditional expression (such as bool or HRESULT etc)?
Wouldn't it be safer to pass in both the buffer and a reference to a bool
(or HRESULT) indicating success (ie. instead of returning said value)?
void ReadRegistryDword(LPCTSTR strKeyName, DWORD& dwKeyValue, bool&
bSuccess);
With the above function it is impossible for me to proceed to make use of
dwKeyValue until a sequence point has been reached, after which dwKeyValue
will be valid if and only if bSuccess is true.
bool bSuccess;
DWORD dwKeyValue;
ReadRegistryDword("SomeKeyName", dwKeyValue, bSuccess);
// Well defined conditional
if(bSuccess && dwKeyValue != 0)
{
puts("Key value non zero");
}
-------------------------
Thank you in advance for your time and patience,
- Alan Carre