while loop

May 12, 2014 at 12:23pm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 unsigned long
    hash(unsigned char *str)
    {
        unsigned long hash = 5381;
        int c;

        while (c = *str++)
            hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

        return hash;
    }




this algorithm (k=33) was first reported by dan bernstein many years ago in comp.lang.c. another version of this algorithm (now favored by bernstein) uses xor: hash(i) = hash(i - 1) * 33 ^ str[i]; the magic of number 33 (why it works better than many other constants, prime or not) has never been adequately explained.

Please, can someone explain me meaning of :
while (c = *str++)

When does this "while loop" stop?

Many thanks!!!
May 12, 2014 at 12:36pm
Let's break down the expression c = *str++

str++ increments the str pointer and returns the old value of the pointer before it was incremented.

*str++ dereferences the pointer which gives you an unsigned char.

c = *str++ assigns the unsigned char to the variable c, and returns the value of c (after it was assigned).

The loop will run as long as the condition is non-zero so in other words the loop will stop when it find the first zero byte.
May 12, 2014 at 12:38pm
First you do dereference an uchar pointer and assign (copy) the value to integer variable.
Then you increment the pointer to point to the next character in the string.
Last the value of the expression, i.e the new value of 'c', is used as the condition.

What is the value of the end-of-string character in C-style strings? '\0'.
What is that as integer? 0
What is that as bool? false
May 12, 2014 at 12:41pm
THANKS; Peter87, and kaskiverto, I owe U for that!!!
(Task in my book is completely unclearly written, this confuses on the very begiinning!!!!- I thought they thought sth completely diferent!!!)

MANY THANKS!!!
Last edited on May 12, 2014 at 4:54pm
Topic archived. No new replies allowed.