val % size >= size?!

I have this short question: under what obscure circumstances can this happen?
What type is val and size?
Unless I'm mistaken, this will be true when size is negative and val > size (e.g. val = -1 and size = -2). I don't know if this makes sense within the context of your program, but it certainly is possible for the expression to be true.
Last edited on
And how about this:

1
2
3
4
5
6
7
8
9
10
11
12
13
unsigned int size_ = 123;
const unsigned int hash( char* key ) const
{
    unsigned int val = 0;
    while ( *key )
    {
        val = val<<1 ^ *key;
        key++;
    }
    if ( val < 0 )
        return (-val) % size_;
    return val % size_;
}

Is the statement impossible there? Also, please tell me, if its completely safe to assume, that bit shifting wont make negative result! (should be, but I am not sure...)
Last edited on
As you are working with unsigned types you can't get negative values and val would never be less than zero so line 11 would never be executed
Interesting, I should delete or compiler is able to optimise code and avoid testing? It can be, that leaving those couple of lines is useful...
val is unsigned. unsigneds can never be negative. Lines 10 and 11 can safely be removed as never executing. (If you compiled with warnings turned on you'd get a "warning: comparison of unsigned vs. signed" warning and possibly also a "comparison is always false due to limited range of data type" on line 10).

EDIT: well, so actually, g++ gives no warnings at all, even with -Wall... but still, the code can never execute.
Last edited on
Topic archived. No new replies allowed.