Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `(c = *str) != 0` mean?

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?

like image 994
Maxfield Avatar asked Jan 04 '23 06:01

Maxfield


2 Answers

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.

like image 140
Sergey Kalinichenko Avatar answered Jan 11 '23 22:01

Sergey Kalinichenko


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.

like image 28
Bathsheba Avatar answered Jan 11 '23 23:01

Bathsheba