I'm having a little difficulty trying to understand what setting a for loop's test condition to a pointer does exactly, or even setting it to a variable value without any comparison. One code example I'm working with on my homework is:
int f ( char *s, char *t) {
char *p1, *p2;
for (p1 = s; *p1; p1++) {
for (p2 = t; *p2; p2++)
if (*p1==*p2) break;
if (*p2 == ‘\0’) break;
}
return p1-s;
}
I'm not looking for an explanation of the function, more of just an explanation of the test condition on the two for loops.
for (p1 = s; *p1; p1++) {
for (p2 = t; *p2; p2++) {
It's equivalent to comparing *p1
and *p2
to NUL ( \\0
). The loops will terminate when the strings' NUL terminators are reached.
for (p1 = s; *p1 != '\0'; p1++) {
for (p2 = t; *p2 != '\0'; p2++) {
You can use this shorthand in if
and while
statements as well, and for other types. Leaving out the condition checks the variable against the default zero value for its type: '\\0'
for characters, 0
for integers, 0.0f
or 0.0
for floats and doubles, NULL
for pointers.
p = malloc(n);
if (p) {
// if p is not null
}
int len = strlen(s);
while (len--) {
// loop until len reaches 0
}
for (p1 = s; *p1; p1++)
继续执行循环,而*p1
为真,即地址p1
处的字符值非零,即p1
未指向NUL字节。
Each character in the outer loop:
for (p1 = s; *p1; p1++) {
}
is tested character per character against the inner loop using pointer arithmetic and if there is match then break
for (p2 = t; *p2; p2++)
if (*p1==*p2) break;
End of character or is NULL for inner loop then break from the loop also
if (*p2 == ‘\0’) break;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.