在以下代码中:
int strlen(char *s){
char *p = s;
while(*p++ != '\0');
return p - s;
}
为什么上述评估与此不同:
int strlen(char *s){
char *p = s;
while(*p != '\0') p++;
return p - s;
}
我的理解是表达式将首先评估,然后递增。
p
无论while()
条件是真还是假,第一个代码中的值都会递增。
在第二段代码中,p
仅当while
条件为真时才递增。
Consider the last step in while loop when *p = '\0'
.
In 1st code:
while(*p++ != '\0');
p
still get one increment, and pointer to the element behind '\0'
.
In 2nd code:
while(*p != '\0') p++;
*p != '\0'
is not true, so while loop end, p get no increment. p
pointer to '\0'
.
在第一种情况下:-
while(*p++ != '\0');
p 将在表达式评估后立即递增,而不管条件是真还是假,因为++
它是条件表达式的一部分。
而在第二个中:-
while(*p != '\0') p++;
首先将检查条件,如果为真,则只会增加 p。