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

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

It\'s about strcat function.

while (*p)
    p++;

and

while (*++p)
    ;

both works, but

相关标签:
4条回答
  • 2021-01-07 12:03

    Let's assume that p is a string.

    while (*p) p++; /* (1) */
    while (*++p) ;  /* (2) */
    while (*p++) ;  /* (3) */
    
    • (1) is different from (2) if p is an empty string.
    • (1) is different from (3) because with (3), even if the current value of *p is a '\0' character, p is incremented.
    0 讨论(0)
  • 2021-01-07 12:07

    Both

    while (*p) p++;
    

    and

    while (*++p) ;
    

    will advance p to point to the 0 terminator in a string, whereas

    while (*p++) ;
    

    will advance p to point one character past the 0 terminator.

    To see why, let's assume the following characters in memory:

    Address         0x00 0x01 0x02 0x03
    -------         ---- ---- ---- ----
    0x8000           'a'  'b'  'c'   0
    0x8004           ...
    

    Assume that p starts at address 0x8000. Here's how the first loop plays out:

    1.  *p = 'a'
    2.  p = 0x8001
    3.  *p = 'b'
    4.  p = 0x8002
    5.  *p = 'c'
    6.  p = 0x8003
    7.  *p = 0
    8.  end loop
    

    Here's how the second loop plays out:

    1.  p = 0x8001
    2.  *p = 'b'
    3.  p = 0x8002
    4.  *p = 'c'
    5.  p = 0x8003
    6.  *p = 0
    7.  end loop
    

    And here's the last one:

    1.  *p = 'a'
    2.  p = 0x8001
    3.  *p = 'b'
    4.  p = 0x8002
    5.  *p = 'c'
    6.  p = 0x8003
    7.  *p = 0;
    8.  p = 0x8004
    9.  end loop
    

    In the last version, evaluating *p++ advances the pointer even if the value of *p is 0.

    0 讨论(0)
  • 2021-01-07 12:20

    *++p means increment this variable, then use it
    *p++ means use the variable, then increment it

    0 讨论(0)
  • 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++.

    0 讨论(0)
提交回复
热议问题