Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 808
RhymesWithDuck Avatar asked Aug 27 '26 08:08

RhymesWithDuck


2 Answers

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

like image 84
Fred Larson Avatar answered Aug 30 '26 07:08

Fred Larson


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.

like image 31
Charlie Martin Avatar answered Aug 30 '26 09:08

Charlie Martin