int equiv (char, char);
int nmatches(char *str, char comp) {
char c;
int n=0;
while ((c = *str) != 0) {
if (equiv(c,comp) != 0) n++;
str++;
}
return (n);
}
What does "(c = *str) != 0" actually mean? Can someone please explain it to me or help give me the correct terms to search for an explanation myself?
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.
Confusingly,
while ((c = *str) != 0) {
is a tautology of the considerably easier to read
while (c = *str) {
This also has the effect of assigning the character at *str
to c
, and the loop will terminate once *str
is \0
; i.e. when the end of the string has been reached.
Assignments within conditionals such as the above can be confusing on first glance, (cf. the behaviour of the very different c == *str
), but they are such a useful part of C and C++, you need to get used to them.
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