3

在以下代码中:

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;
}

我的理解是表达式将首先评估,然后递增。

4

3 回答 3

10

p无论while()条件是真还是假,第一个代码中的值都会递增。

在第二段代码中,p仅当while条件为真时才递增。

于 2013-07-14T05:36:30.570 回答
2

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'.

于 2013-07-14T08:08:14.413 回答
0

在第一种情况下:-

while(*p++ != '\0');

p 将在表达式评估后立即递增,而不管条件是真还是假,因为++它是条件表达式的一部分。

而在第二个中:-

while(*p != '\0') p++;

首先将检查条件,如果为真,则只会增加 p。

于 2013-07-14T05:41:08.593 回答