-1

I am just curious why would the two functions produce different results.

unsigned long Hash1(const string s)
{

    int length = s.length();
    unsigned long h = 1;

    for (int i = 0; i < length; i++)
        h *= 101 + (unsigned long)s[i];

    return h;
}

unsigned long Hash2(const string s)
{

    int length = s.length();
    unsigned long h = 1;

    for (int i = 0; i < length; i++)
        h = h * 101 + (unsigned long)s[i];

    return h;
}

int main()
{
    cout << "Value of hash1 = " << Hash1("kelvin@gmail.com") << endl;
    cout << "Value of hash2 = " << Hash2("kelvin@gmail.com") << endl;

    system("pause");
    return 0;
}

Isn't h *= 101 + (unsigned long)s[i] equals to h = h * 101 + (unsigned long)s[i]?

This is the output:

Value of hash1 = 1693843456

Value of hash2 = 2162085645

Thank you for your help!!!

Glory Sky
  • 7
  • 2
  • 2
    http://en.cppreference.com/w/cpp/language/operator_precedence – chris Dec 04 '17 at 02:45
  • 1
    You don't have `h*= 101` or `h = h * 101`. You have `h *= 101 + (unsigned long)s[i]` and `h = h * 101 + (unsigned long)s[i]`. – user2357112 Dec 04 '17 at 02:46
  • You're actually telling it..`h = h * (101 + s[i])`.. In other words, h = itself multiplied by the entire right side expression. – Brandon Dec 04 '17 at 02:50

2 Answers2

2

Isn't h *= 101 + (unsigned long)s[i] equals to h = h * 101 + (unsigned long)s[i]?

No, due to operator precedence, h *= 101 + (unsigned long)s[i] is equivalent to h *= (101 + (unsigned long)s[i]), which is the same as h = h * (101 + (unsigned long)s[i]).

The difference between the two is the difference between computing:

h = h*(a+b)

and

h = h*a + b
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

Answers are already given in the comments to the question, but just to expand on the question, the two statements

h *= 101;

h = h * 101;

are indeed equivalent. But when used inside of larger expressions, *= has very low precedence. * has the highest precedence, then +, then *=. So

h *= 101 + x;

is the same as:

h = h * (101 + x);

Now, if you wanted

h = (h * 101) + x;

you could have written:

(h *= 101) += x;

which works because the *= operator returns a reference to the left hand side. However, this doesn't really look great.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232