weird while!

hello i have a problem with understanding the while in this code (which are bold)
could anyone help me why they haven't any expression?


int w(char c[]){
int ct=0, k=0;
char ch=' ';
while(ch != '\0'){
while((ch=c[k++]) == ' ');
if(ch=='\0') break;
ct++;
while((ch=c[k++])!='\0' && ch!=' ');
}
return(ct);
}
gesh.. those C-hacker.. Code like this is one of the reasons people don't talk to C-Programmer at cocktail parties! :-D


Anyway, while loops over its body as long as an expression is true. Now, it's body is just ";" so its empty.
But nobody said that the expression can't have any side effect. Here, the expression indeed assigns a value and increases a counter.

(ch=c[k++]) == ' '
When the compiler try to find out whether this is true or false, he sees, that this is actually the same like:

1
2
char temp = ch=c[k++];
temp == ' ';


Now the first statement is even composed of three things: Two assignments and one increment. Without the first assignment, you could write it like this*):

1
2
3
ch=c[k++];
char temp = ch;
temp == ' ';


And finally, "ch=c[k++]" are two statements and can be written as:

1
2
3
4
ch=c[k];
k++;
char temp = ch;
temp == ' ';


So it means: assign the value of c[k] to ch. Then increase k. If the value before the increase (stored in ch) is ' ', then still loop.

And that was only the first while loop. Now good luck figuring out how this fits into the outer loop.


Ciao, Imi.
*) That's not 100% right, but right enough for the case here ;-). The ignorable difference is, that actually = returns the second operand, not the first.
thanks, i got it
Topic archived. No new replies allowed.