开发者

The unary increment operator in pointer arithmetic

开发者 https://www.devze.com 2023-02-01 00:17 出处:网络
t开发者_开发百科his is my first post. I have this function for reversing a string in C that I found.

t开发者_开发百科his is my first post.

I have this function for reversing a string in C that I found.

    void reverse(char* c) {
        if (*c != 0) {
            reverse(c + 1);
        }
        printf("%c",*c);
    }

It works fine but if I replace:

reverse(c + 1);

with:

reverse(++c);

the first character of the original string is truncated. My question is why would are the statements not equivalent in this instance?

Thanks


Because c + 1 doesn't change the value of c, and ++c does.


Let's expand on Fred's answer just a bit. ++c is equivalent to c = c+1, not c+1. If you replace the line reverse(c+1) with reverse(++c), then c is changed. This doesn't matter as far as the recursive call is concerned (why?) but means c is pointing somewhere new in the printf.


c + 1 does not alter c,

++c increments c and then uses the new value in your replaced recursive call, reverse(++c)


As noted, ++c changes the value of c but c+1 does not.

This does not matter in the recursive call itself: reverse(c+1) and reverse(++c) will pass the same value to reverse; the difference happens when you use c in a printf after the recursive call -- in the ++c case, the value of c has been changed by the time you reach the printf.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号