what difference between while(*p){p++;} ,while (*++p){;} and while(*p++){;}?

前端 未结 4 1812
日久生厌
日久生厌 2021-01-07 11:45

It\'s about strcat function.

while (*p)
    p++;

and

while (*++p)
    ;

both works, but

4条回答
  •  独厮守ぢ
    2021-01-07 12:27

    // move p forward as long as it points to a non-0 character,
    // leave it pointing to a 0 character.
    while (*p) p++;  
    
    // move p forward until it points to a 0 character, skipping the first 
    // character before you start
    while (*++p);
    
    // move p forward until it points one past a 0 character
    while (*p++);
    

    So given that (1) "works": (2) also works if p initially points to a non-empty string. (3) doesn't work at all because p ends up pointing to a different place.

    *++p increments p and then evaluates to whatever p now points to. *p++ evaluates to whatever p initially points to, but also increments p. Hence (2) and (3) are different.

    (1) and (3) are different because (3) executes the p++, then it decides whether to stop. (1) first looks at *p to decide whether to stop, and if not stopping it executes the p++.

提交回复
热议问题