Search code examples
chashhashtablehashcode

C Warning: Statement with no effect for hashing string


I am trying to hash a string and I got the code from my textbook.

Here's the code:

int hash(char *str) {
  int i, sum;
  for (sum = 0; i = 0; str[i] != '\0'; i++)
    sum += (int) str[i];
  return sum % MODVAL;
}

The code giving me the error is str[i] != '\0';


Solution

  • C for loop syntax is composed of 3 expressions

    for (initialization; condition; increment)
    

    In your code you have four expression in your for loop declaration. If you want multiple initialisations (e.g. initialize sum and i to zero), you can delimit them with a comma instead:

    for (sum = 0, i = 0; str[i] != '\0'; i++)
        // ...