Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can char* be a condition in for loop?

Tags:

c++

c

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:

  1. how can *s be a condition? what does it mean?

  2. what does "h=(h*17)^*s" mean?

Thanks for help!

like image 944
Jackie Avatar asked Apr 16 '10 15:04

Jackie


2 Answers

  1. 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).

  1. what does "h=(h*17)^*s" mean?

It multiplies h by 17 then xors it with the value pointed to by s.

like image 112
James McNellis Avatar answered Sep 18 '22 12:09

James McNellis


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.

like image 45
Thomas Pornin Avatar answered Sep 20 '22 12:09

Thomas Pornin