trying to find the error

M

mdh

K & R 5-5 asks for a strncat function ( concat n characters of t);

void mystrncat(char *s, char *t, int n)

{

while ( *s++); /* find end of s */ /* <<<<< 1 */

/* stops at '\0' */ /* <<<<<2 */

while ( *t && n-- > 0)

*s++ = *t++; /* /*<<<<< 3 */

while ( n -- > 0);
*s++ = '\0';

}

Now, with 1 I **Thought** that *s++ fails when *s == '\0', so that s
points to '\0'.
So, when 3 occurs, I thought the first char of t ( *t) is assigned to
the "Old" position of s, which should be '\0', but it is not.
What am I missing.
Thanks in advance.
 
M

mdh

     The loop stops when `s' points at '\0' *before* being
incremented, but the increment happens regardless of the
outcome of the test.

May I just ask this. I recently had an extensive explanation about
this from one of the members of the group. Is this then a fair
statement about what happens.
When the loop fails, it is still proceeds to the next sequence point.
In other words, it is not like a "break" statement in a loop.
thanks
 
I

Ian Collins

mdh said:
May I just ask this. I recently had an extensive explanation about
this from one of the members of the group. Is this then a fair
statement about what happens.
When the loop fails, it is still proceeds to the next sequence point.
In other words, it is not like a "break" statement in a loop.

The loop does not fail, the test yields false. The expression "s++" is
always evaluated before the result of the expression is tested.

If you want s to point to the end of the string, use

while( *s ) { s++; }
 
J

jt

thank you.

and moreover the unary operators are right to left associative.since
here its post incrementation,s is incremented in the next statement.
probably you can overcome this by using

while(*s)s++;
 
I

Ian Collins

jt said:
and moreover the unary operators are right to left associative.since
here its post incrementation,s is incremented in the next statement.

s++ is the statement, there isn't a next one.
probably you can overcome this by using

while(*s)s++;

Which is exactly what I wrote....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top