Let's assume I want to write a function that concatenates two strings in C. The way I would write it is:
void concat(char s[], char t[]){
int i = 0;
int j = 0;
while (s[i] != '\0'){
i++;
}
while (t[j] != '\0'){
s[i] = t[j];
i++;
j++;
}
s[i] = '\0';
}
However, K&R in their book implemented it differently, particularly including as much in the condition part of the while loop as possible:
void concat(char s[], char t[]){
int i, j;
i = j = 0;
while (s[i] != '\0') i++;
while ((s[i++]=t[j++]) != '\0');
}
Which way is preferred? Is it encouraged or discouraged to write code the way K&R do? I believe my version would be easier to read by other people.
while (*s++ = *t++);
(My C is very rusty, do I need parens there for operator precedence?) Did K&R release a new version of their book? Their original book had extremely concise and idiomatic code.'\0'
fromt
(thewhile
exits first). This will leave the resultings
string without a terminating'\0'
(unless the memory location was already zeroed). The second code block will make the copy of the terminating'\0'
prior to exiting thewhile
loop.