Recently I've been learning C and pointers.
In the book Programming in C by Stephen G. Kochan, I've met an example which I have difficulties of fully understand it.
To copy string from
to string to
using pointers, the example indicates:
void copyString (char *to, char *from) {
while ( *from )
*to++ = *from++;
*to = '\0';
}
In my understanding, *from++
is a post-increment of *from
; thus the value of *to++
should be *from
only.
For instance, if
`*from` is in the position 1.
`*from++` is in position 2
`*to++` in position 2,
But: *from++ = *to++
should return values of *from
as *to
position 1, not 2.
The compiler said it's position 2, the book also said it's position 2.
I'm a little bit confused here. Do you have any feasible explanation for this case?
When using the postfix ++
unary operator, the increment is sequenced after the computation of the value of the operand. So the expression is equivalent to:
*to = *from;
to++ ;
from++ ;
In your example: *to++ = *from++;
, the values of *to
and *from
are obtained and then the value of *from
is assigned to *to
, then both pointers are incremented.
*to++ = *from++;
both to
and from
have post increment.
You can read like,
*from
to *to
to
and from
. The postfix operators are evaluated and the operation of increment (decrement) is performed once the evaluation of assignment operator =
has finished. So, first the values are copied, then both the pointers are incremented.
As a supplyment to previous answer.
In C, suffix increment ++
has higher precedence than dereference operator *
, which means *ptr++ is equivalent to *(ptr++). Check this for more info about operator precedence of C.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.