0

I am making a multiplicative string hash function and my for-loop is throwing an error. I am attempting to iterate through each character in the string value by using its length.

The error: hashtable.cpp:29:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::__cxx11::basic_string<char>::size_type’ {aka ‘long unsigned int’} [-Wsign-compare] for (int i = 0; i < key.length(); i++)

Hash function:

int HashTable::Hash(string key)
{
    int hash = 5381; //initial value

    for (int i = 0; i < key.length(); i++)  //line that is causing error
    {
        hash = (hash * 33) + (int)key[i];

    }               

    return hash % size;

}

Is there another way to write my condition statement to avoid this error?

xCyberBeex
  • 17
  • 6
  • 2
    change `int i` to `size_t i` – Ardent Coder Apr 05 '20 at 23:04
  • 1
    That worked, thank you. I would ask what size_t does but I will look around for that answer. – xCyberBeex Apr 05 '20 at 23:07
  • 1
    Glad it helped :) For the new question, you can see [this](https://stackoverflow.com/questions/502856/whats-the-difference-between-size-t-and-int-in-c) – Ardent Coder Apr 05 '20 at 23:09
  • What you are calling an 'error' is not a compiler report about an error. Note the word 'warning: ' after the '.cpp:29:20:". Please google and review "what is the difference between a compiler warning and an error' – 2785528 Apr 06 '20 at 00:09

1 Answers1

2

length() returns size_t which is unsigned. Mixing signed (i) with unsigned (key.length()) is problematic so this is what the error is about.

You can:

  • use std::size_t i
  • use static_cast<int>(key.length())
  • better yet use range for for (auto ch : key)
bolov
  • 72,283
  • 15
  • 145
  • 224