5

What difference between while (* p) {p ++;}, while (* ++ p) {;} and while (* p +...

 3 years ago
source link: https://www.codesd.com/item/what-difference-between-while-p-p-while-p-and-while-p.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

advertisements

It's about strcat function.

while (*p)
    p++;

while (*++p)
    ;

both works, but

while (*p++)
    ;

does not work. I think first and third should be same, but it's not.


while (*p) p++;

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK