#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    109
    Rep Power
    2

    Shortened version of STRCPY()-- where does it test for NULL ?


    I saw this version of strcpy in a C book:

    void strcpy(char *s, char *t)
    {

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

    }

    How does it know when to stop the copying?

    There is another version that is almost identical, where they added ((*s++=*t++)!='\0') to the while loop and i quote them: "the comparison against '\0' is redundant".

    Also, what is the exact priority of the operators in the second case:

    while((*s++=*t++)!='\0')

    Thanks in advance.
  2. #2
  3. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,073
    Rep Power
    1802
    In C assignment is an expression rather than a statement. That is to say it has a result value like any other expression.

    The result of an assignment expression is the value of the right-hand-side. It is this attribute that allows expresions such as:
    Code:
    a = b = c = d = 0 ;
    In your case the loop terminates when *t++ is zero - i.e. when the next character in the source string is nul.

    Originally Posted by C learner
    Also, what is the exact priority of the operators in the second case:

    while((*s++=*t++)!='\0')
    The mere fact that you have to ask is one good reason not to write expressions like that. It may be "clever" but it is not "smart". It has its place perhaps in library code but clarity is not served by such expressions.

    The honest answer is I don't know, but to find out would be simple enough but not effective use of my time. It is sufficient to realise that the the rules are arcane and often undefined, so the truly smart programmer avoids the issue altogether and never uses ++ or -- (post or pre) in an expression where other operators are involved. So essentially restricting use to:

    Code:
    a++;
    a-- ;
    ++a ;
    --a ;
    Brian Kernighan said this:
    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
    Worth remembering.

    Comments on this post

    • dwise1_aol agrees : Good quote! That belongs in somebody's signature.
    • eramit2010 agrees
    Last edited by clifford; July 28th, 2013 at 06:02 AM.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    109
    Rep Power
    2
    Thanks :)

IMN logo majestic logo threadwatch logo seochat tools logo