Search code examples
crecursionfunction-definitionpost-incrementpre-increment

`++` and `+=` operator are behaving differently


I have a code which print pointer to const char, or I mean a string, recursively. My code works fine when I'm using += operator to call print() function. But, when I'm using ++ operator my code goes to an infinite loop just printing 'H'.

Here's my code: TRY IT

#include <stdio.h>

void print(const char *s){
    if(*s == 0)
        return;
    putc(*s, stdout);
    print(s += 1); // infinite loop when `s++`
}

int main(void){
    print("Hello");
    return 0;
}

I know that in any loop for an example:

for(size_t i = 0; i < 10; i++) { }

is completely equivalent to

for(size_t i = 0; i < 10; i += 1) { }

Then, please tell what I'm missing out?


Solution

  • You are using the (postfix) post-increment operator ++ the value of which is the value of the operand before incrementing. So you are calling the function with the same value of the pointer. You need to use the pre-increment operator ++

    void print(const char *s){
        if(*s == 0)
            return;
        putc(*s, stdout);
        print( ++s ); 
    }
    

    From the C Standard (6.5.2.4 Postfix increment and decrement operators)

    2 The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it).

    As for the for loop

    for(size_t i = 0; i < 10; i++) { }
    

    then the value of the expression i++ is not used. The variable i is used after applying the side effect of incrementing it by the operator. To check this you could write the for loop the following way

    for(size_t i = 0; i < 10; printf( "%zu ", i++ ) ) { }