RhymesWithDuck
RhymesWithDuck

Reputation: 25

The unary increment operator in pointer arithmetic

this 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

Upvotes: 2

Views: 667

Answers (4)

Mitch Wheat
Mitch Wheat

Reputation: 300797

c + 1 does not alter c,

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

Upvotes: 2

David Gelhar
David Gelhar

Reputation: 27900

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.

Upvotes: 1

Charlie Martin
Charlie Martin

Reputation: 112424

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.

Upvotes: 4

Fred Larson
Fred Larson

Reputation: 62113

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

Upvotes: 7

Related Questions