operator precedence

Given

t is char array 'hello'
and s is empty char array

first, we evaluate primary expression operator () inside while loop condition. Inside that, expr++ is highest precedence and so we evaluate left to right. Since s is a pointer, which points to the address of the first element of the char array passed from calling function, we can use pointer arithmetic to increment to the next char stored in memory. We use the same process for t.

And then we use * unary dereference operator to return the value stored at that memory location. So we dereference 'h' from t and set it into s. Then () returns the value of s which is 'h'.

Then we use the comparison operator != to compare value on left with value on right.

1
2
3
4
5
void strcpy(char *s, char *t) 
{ 
	while ((*s++ = *t++) != '\0')
		;
}


What I don't understand is it uses pointer arithmetic to move to the next memory location without assigning the value at the first memory location to s (since = has lower precedence), before moving to next memory location. So it seems it's not copying the first value over. Am I missing something?
Ok I took another look at this and notice it is using postfix operator and not prefix operator. That means even though postfix primary expression operator ++ has higher precedence than unary dereference operator *, when we increment to next memory position, that doesn't happen right away. It happens only after the assignment, right? So the return value of () is actually what FIRST element of s evaluates to.
it uses pointer arithmetic to move to the next memory location without assigning the value at the first memory location to s


You're missing the semantics of post-increment. Post-increment makes and returns a copy of its argument, which is holding the value before the increment. It doesn't matter what happens to s or t: the indirection operators work on the copies of their old values, and the assignment operator works on the results of the indirection operators.
Topic archived. No new replies allowed.