views:

117

answers:

4

To compile my C++ code I use the -W flag, which causes the warning:

warning: comparison of unsigned expression < 0 is always false

I believe this was considered as a bug and was fixed on version GCC 4.3, but I'm using GCC 4.1

Code that is obviously offending here:

void FieldGroup::generateCreateMessage (const ApiEvent::GroupData &data, omsgstream &result) const {
  dblog << debug;

  // Write out the data fields we care about, in the order they were specified
  for (size_t index = 0; index < fields.size(); ++index) {
    size_t esIndex = clsToES[index];
    if (esIndex < 0 || esIndex >= data.fields.length()) {
      ostringstream buf;
      buf << "Invalid field " << index << " (index in ES data set " << esIndex << ", " << data.fields.length() << " fields returned)";
      throw InvalidDataException (buf.str());
    }
    fields[index].writeData (data.fields[esIndex], result);
  }
}

Warning I'm getting:

dbtempl.cpp: In member function ‘void ECONZ::FieldGroup::generateCreateMessage(const nz::co::econz::eventServer::ApiEvent::GroupData&, ECONZ::omsgstream&) const’: dbtempl.cpp:480: warning: comparison of unsigned expression < 0 is always false

How can i possibly stop these warnings from appearing? I don't want to remove the -W flag.

+13  A: 

You are testing if a positive value is below 0.

A size_t is unsigned, so at least 0.

This can never happen and the compiler optimize things out by just removing the test. The warning is here to tell you because if someone does that, it might be a mistake.

In your case, you might just remove the test, it should be fine.

ereOn
+2  A: 

Renove the characters esIndex < 0 ||

This part of code is totally meaningless to the machine, which is why the compiler warns you - "did you mean to do something else?".

Pavel Radzivilovsky
+2  A: 

size_t is an unsigned integral type. Hence, the compiler sees that the comparison < 0 will always be false (the Standard does specify 2's complement wrapping when overflow occurs). You should take that comparison out as it is a no-op (and the compiler will probably not generate any code for it).

Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.46

and the corresponding footnote:

46) This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.

dirkgently
A: 

How can i possibly stop these warnings from appearing ? I don't want to remove -W flag.

:|

Just correct your code and the warning will disappear ... that's the idea ...

The warnings are there to help you produce correct, cleaner, more efficient code.

Cedric H.