Home > Software Development > When NULL == false in QVariant

When NULL == false in QVariant

December 21st, 2009
I (Nebojsa) spent some time hunting down a problem where our QSettings (a Qt framework settings class) derived convenience class would not read Boolean values properly.
We wrapped the “Read” function with a code similar to this
  
template  T Read(ConstString name, T defaultValue)
{
   T result = defaultValue;  // Assume
     if (Exists(name))
        then QVariant v = this->value(name);
     if (v != NULL)
        then result = v.value();

   return result;
}
The idea is simple – if the value exists we read it, if not we use the supplied default value.
The line
   If (v != NULL)
fails miserably if v is a Boolean value.
If v is a boolean type and its value is false – then the v == NULL expression evaluates to true.
This is understandable since NULL expands to 0 and 0 is considered false. I wish NULL would be reserved for pointers in C++ so that the compiler could complain whenever one tried to use it for anything else but to signify a NULL POINTER!
So rather than testing the QVariant for NULL – use its member function isNull to test if it is really null.
The if statement above should be written as
   If (!v.isNull())   ...
Everything works perfectly afterwards.
Btw. If you are wondering what is a Pascal style “then” doing in our C++ if statements – we believe that “then” is making our if statements much more readable. It is simply defined as nothing
#define then
Categories: Software Development Tags:
Comments are closed.