-2
//function to copy string t to string s using pointers
void strcpy(char *s,char *t)
{
    while((*s++=*t++)!='\0');
    return;
}

i am confused how is the expression *s++==*t++ evaluated.I know associativity of increament operator is higher than assignment operator.

kapil
  • 625
  • 12
  • 20
  • 4
    http://stackoverflow.com/questions/810129/how-does-whiles-t-copy-a-string – Arjun Sreedharan Mar 01 '15 at 10:08
  • thanks Arjun Sreedharan got my doubt cleared. – kapil Mar 01 '15 at 10:17
  • @EdHeal there is nothing 'crappy' in this code. this is a beginner code to understand C strings and pointer and it is ok – David Haim Mar 01 '15 at 10:18
  • 1
    @EdHeal actually it does copy the null character. Similar code to this appears in K&R, maybe you could email Brian Kernighan and let him know he's a crap coder – M.M Mar 01 '15 at 10:22
  • this is a standard use in C. – David Haim Mar 01 '15 at 10:25
  • 2
    He is not god. It is crap code because it is doing lots of thinks in one line of code. I, and the poster, it is hard to debug. I get fed up with programmers trying to be clever and use all the tricks in the book. Does not result in maintainable code – Ed Heal Mar 01 '15 at 10:25
  • @EdHeal: this is pretty much the canonical implementation of `strcpy`, and is perfectly idiomatic C (although it could use some whitespace for better readability). This is what the OP can expect to find in the wild. "Don't do that" isn't going to help him understand it when he finds it. – John Bode Mar 01 '15 at 14:26

2 Answers2

2

*s++=*t++ is basically

*s = *t;
s++;
t++;
David Haim
  • 25,446
  • 3
  • 44
  • 78
1

*s++=*t++ implies that; *s and *t must be evaluated to produce a variable (lvalue) and original values of s and t is used in this process (i.e, the value of s and t before increment) . *t must be assigned before increment of s.

Note that it is not necessary that increments will happen after the assignment. Rather, the original values must be used. As long as the original value is used, the increment can happen at any time.

It should be also noted that the post increment ++ comes after the variable does not mean that the increment will take place after assignment.

Suggested reading: Incrementing Pointers, Exact Sequence.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264