This expression has two parts:
c = *str
- this is a simple assignment of c
from dereferencing a pointer,
val != 0
- this is a comparison to zero.
This works, because assignment is an expression, i.e. it has a value. The value of the assignment is the same as the value being assigned, in this case, the char
pointed to by the pointer. So basically, you have a loop that traces a null-terminated string to the end, assigning each individual char
to c
as it goes.
Note that the != 0
part is redundant in C, because the control expression of a while
loop is implicitly compared to zero:
while ((c = *str)) {
...
}
The second pair of parentheses is optional from the syntax perspective, but it's kept in assignments like that in order to indicate that the assignment is intentional. In other words, it tells the readers of your code that you really meant to write an assignment c = *str
, and not a comparison c == *str
, which is a lot more common inside loop control blocks. The second pair of parentheses also suppresses the compiler warning.
str
and assigns the value it points to toc
and then comparesc
to zero.*str
takes value from address ofstr
;c = *str
assigns this value toc
;(c = *str) != 0
checks if this value is notNULL
.NULL
is the end of string marker in C/C++, see "null terminated string" en.wikipedia.org/wiki/Null-terminated_stringNULL
is used the depict null-pointer, not nul termination. Mixing those causes confusion. Also, no answers in comments, please.