Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

K&R contains this beautiful koan-like string copy code:

    while (*t++ = *s++)
        ;
Honestly the elegance of this thing was one of the hooks that made me fall in love with C. But this was from a now-forgotten age of innocence, as there are so many "nopes" around this line-and-a-half that one would, rightly, be tarred and feathered for ever putting it in a program today.


Could you explain why this line should be discouraged? I'm a beginner in C, so I really don't know. That's why I'm asking.


while (t++ = s++) ;

You're assigning a char to another, relying on the return value being 0 to detect end of string.

You're performing the copy while also increasing the pointers with ++ in the same expression.

You're using the cryptic ; empty statement to signify nop, thereby confusing newbies.

Etc


Another reason, in addition to other replies and separate from safety concerns, is that strcpy, memcpy etc are nowadays usually implemented via more efficient compiler intrinsics rather than an explicit loop.


Equivalent of a strcpy() there's no bounds checking.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: