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

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

It\'s about strcat function.

while (*p)
    p++;

and

while (*++p)
    ;

both works, but

4条回答
  •  误落风尘
    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.

提交回复
热议问题