In a book I am reading there is a piece of code :
string x;
size_t h=0;
for(const char* s=x.c_str();*s;++s)
h=(h*17)^*s;
Regarding this code, I have two questions:
how can *s
be a condition? what does it mean?
what does "h=(h*17)^*s"
mean?
Thanks for help!
- how can *s be a condition? what does it mean?
It means "while the value pointed to by s
is not zero." C strings are null-terminated, so the last character in the string returned by c_str()
will be the null character (\0
, represented by all bits zero).
- what does "h=(h*17)^*s" mean?
It multiplies h
by 17
then xor
s it with the value pointed to by s
.
In C (or C++) any value can be used as a "boolean". A numeric value of 0, or a NULL pointer, means "false". Anything else means "true".
Here, *s
is "the character value currently pointed to by s
". The loop stops if that character is a 0 (not the "0
" digit, with ASCII encoding 48, but the byte with ASCII encoding 0). This is conventionally the "end-of-string" marker, so the loop stops when it reaches the end of the string.
"^
" is the bitwise XOR operator. The left "*
" is a plain multiplication, while the other "*
" is the pointer dereference operator (i.e. the thing which takes the pointer s
and looks at the value to which this pointer points). "=
" is assignment. In brief, the value of h
is multiplied by 17, then XORed with the character pointed to by s
, and the result becomes the new value of h
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With