2

I am concatenating a string (t) at the end of another string (s) in this code but stuck in the use of operators and their precedence in the loop ( while() )

1.while(*s++); doesn't do the work

2.while(*s) ++s; does

But what is the difference between them ?

#include<stdio.h>
void strcat(char *, const char *);

int main(void){
    char s[100] = "Aditya ";
    char t[100] = "Kumar";
    strcat(s, t);
    printf("%s ", s);
    return 0;
}

void strcat(char * s, const char * t){
    while(*s)
        s++;

    while(*s++ = *t++);
}

Why in the strcat() function in first while while(*s++); doesn't concatenate the string but while(*s) s++; does I guess they work the same way ?

5
  • First *s is evaluated and then s++ ? Commented Oct 11, 2017 at 19:40
  • Please elaborate with reference to operator precedences. Commented Oct 11, 2017 at 19:41
  • Because of extra one increment in the first variant. Commented Oct 11, 2017 at 19:42
  • Possible duplicate of C++ Operator priority =, * and ++ Commented Oct 11, 2017 at 19:44
  • @JohnnyMopp no, it's not a duplicate of that. Here the issue is incrementing the pointer no matter what, failing the next loop because s if 1 too much. Commented Oct 11, 2017 at 19:48

1 Answer 1

2

they aren't equivalent.

while(*s++);

increments the pointer no matter what, so when *s is \0, the pointer is incremented once more. And the concatenation happens after the nul-terminator. The rest of the buffer contains zeroes so it doesn't crash but it doesn't do the job.

while(*s) { s++; }

stops when *s is \0. So no extra incrementation is performed.

Sign up to request clarification or add additional context in comments.

9 Comments

To be honest, I answered because it took me a while to figure that out :)
@Jean-FrançoisFabre Your "a while" was approximately 20 seconds to my estimation :P
Does it mean that it is a nice question ?
@Adityakumar Let the score speak for it.
It‘s an interesting brain-twister but not a suitable real-world solution for string concatenation because of the missing boundary checking. Only strings that are guaranteed to be null-terminated and not to exceed 100 characters (together!) are allowed. Otherwise memory overrun occurs.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.