How Does Loop In strcpy Work?

A

A_StClaire_

guys,

this is the code for strcpy, as most of you probably know and I found
out recently:


void str_copy(char* ptr1, char* ptr2) {
for( ; *ptr1 = *ptr2; ++ptr1, ++ptr2);
}


my question is, what the heck kind of loop is that? i.e., how is the
'condition' expression used for assignment like that?

thx
 
I

Ian

guys,

this is the code for strcpy, as most of you probably know and I found
out recently:


void str_copy(char* ptr1, char* ptr2) {
for( ; *ptr1 = *ptr2; ++ptr1, ++ptr2);
}


my question is, what the heck kind of loop is that? i.e., how is the
'condition' expression used for assignment like that?
*ptr1 = *ptr2 will yield something other that 0 while *ptr2 isn't '\0'.

Ian
 
K

Karl Heinz Buchegger

guys,

this is the code for strcpy, as most of you probably know and I found
out recently:

void str_copy(char* ptr1, char* ptr2) {
for( ; *ptr1 = *ptr2; ++ptr1, ++ptr2);
}

my question is, what the heck kind of loop is that? i.e., how is the
'condition' expression used for assignment like that?

In C++ even an assignment has a result. This is eg. what enables
you to write
i = j = k = 5;
 
M

Mike Wahler

guys,

this is the code for strcpy, as most of you probably know and I found
out recently:

It might or might not be, depending upon the implementation.
The language standard does not mandate such implementation
details, only behavior.
void str_copy(char* ptr1, char* ptr2) {
for( ; *ptr1 = *ptr2; ++ptr1, ++ptr2);
}


my question is, what the heck kind of loop is that?

It's a plain, everyday 'for' loop.
i.e., how is the
'condition' expression used for assignment like that?

The value of an assignment expression is that of the
= operator's right-hand operand. I.e. The value of
the expression 'x = 42' is 42.

Above, the 'for' loop's conditional expression is
'*ptr1 = *ptr2', which gives the expression the same
value as '*ptr2'. It will evaluate to true as long
as the character pointed to by 'ptr2' is not zero
(i.e. the string terminator).

-Mike
 

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,755
Messages
2,569,536
Members
45,016
Latest member
TatianaCha

Latest Threads

Top