Home > Enterprise >  ` ` and ` =` operator are behaving differently
` ` and ` =` operator are behaving differently

Time:02-28

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?

CodePudding user response:

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   ) ) { }

CodePudding user response:

s is a post-increment. It returns the original value of s, not the incremented value. This means that

print(s  );

is equivalent to

print(s);
s  ;

Since print(s) calls print(s), you get an infinite loop.


To get the value of s after it's been incremented, use a pre-increment.

print(  s);

This is equivalent to

  s;
print(s);

Finally, there's no reason to change s. You should simply use

print(s 1);
  • Related