Klocwork says that "comparison of unsigned value against 0 is always true", on the following condition line:
#define MAX_VALUE 8589934592 //2^33
...
uint64_t val = get_val();
if (val >= MAX_VALUE)
{
return ERROR_INVALID_VALUE;
}
Why? MAX_VALUE isn't 0...
Please advise.
Thank you in advance.
That literal might be a problem, depending on which version of C++ you're using and how your compiler chooses to treat it.
In the 2003 standard, an unsuffixed decimal literal is of type
int
if it's in the range ofint
, or of typelong int
if it's in the range oflong int
; otherwise, the behavior is undefined. If your version of gcc conforms to the 2003 standard, the undefinedness of the behavior could likely manifest itself as8589934592
evaluating to 0, which would explain the problem you're seeing. (But I'd expect a warning about the integer literal being out of range; did you get such a warning?)In the 2011 standard, such a literal can be of type
int
,long
, orlong long
. (C++ 2003 doesn't havelong long
; it was borrowed from C99.)(Note that
^
is the bitwise xor operator; C++ has no exponentation operator. That doesn't matter much in a comment, but2**33
might be clearer, even though that's not a valid C++ expression either.)What type does
get_val()
return? That shouldn't affect the warning, but it would be interesting to know.If
long
is 64 bits on your system, then this should be ok. Iflong
is 32 bits, thenuint64_t
would have to be something wider thanlong
/unsigned long
-- which implies that your compiler is not operating in conforming C++ 2003 mode.What output do you get for the following program?
and what warning, if any, does Klocwork give you on the comparison? If Klockwork gives you a warning that's inconsistent with the output of the program, this could be a bug in Klocwork (which you should report) -- or you might just need to invoke it with different options. (I've never used Klocwork myself.)
You might be able to solve (or at least work around) the problem by invoking g++ with
-std=c++0x
.