Search code examples
crecursionc-stringspost-incrementfunction-declaration

Why ++str and str+1 is working and str++ isn't?


I know that here are some explanations about the difference between p++, ++p and p+1 but I couldn't understand it clearly yet, especially when it's not working with that function:

void replace(char * str, char c1, char c2){

    if (*str == '\0') {
        return;
    }else if (*str == c1) {
        printf("%c", c2);
    }
    else {
        printf("%c", *str);
    }

    replace(++str, c1, c2);
}

When I do replace(++str, c1, c2); or replace(str+1, c1, c2); it works, but replace(str++, c1, c2); doesn't. Why?


Solution

  • replace(str++, c1, c2); means:

    replace(str, c1, c2);
    str+=1;
    

    while replace(++str, c1, c2); means:

    str+=1;
    replace(str, c1, c2);