zaterdag 16 juni 2007

The Increment/Decrement operators and Pointers

You can use increment operators with pointers as well as with basic variables.

double ar[5] = {21.1, 32.8, 23.4, 45.2, 37.4};
double *pt = ar; // pt points to arr[0], i.e. to 21.1
++pt; // pt points to arr[1], i.e to 32.8

You can also use these operators to change the quantity a pointer points to by using them in conjunction with the * operator. Applying both * and ++ to a pointer raises the questions of what gets dereferenced and what gets incremented.
The PREFIX increment, PREFIX decrement, and DEREFERENCING operators have all the SAME PRECEDENCE.
BUT they associate from RIGHT to LEFT.
The POSTFIX increment and POSTFIX decrement have a HIGHER precedence than PREFIX operators and associate from LEFT to RIGHT.

*++pt; Means right prefix operator is executed first, because it associates from the right to the left, so ++ is to the right of * so first the pointer is incremented, then the value is dereferenced from that incremented pointer, which means the value stored at ar[2].

++*pt; means right to left association, both the postfix increment operator and the dereference operator have the same precedence, however the operators are right to left associative, so first ar[2] is dereferenced and then incremented, to change ar[2] from 23.4 to 24.4

(*pt)++; // increment pointed-to value
The parentheses indicate that first the pointer is dereferenced, yielding 24.4, and then the ++ operator increments that value to 25.4; pt remains pointing at ar[2].

*pt++; // dereference original location, then increment pointer
The higher precedence of the postfix ++ operator means the ++ operator operates on pt, not on *pt, so the pointer is incremented. BUT the fact that the postfix operator is used means that the address that gets dereferenced is the original address, &arr[2], NOT THE NEW ADDRESS. Thus the value of *pt++ is ar[2], or 25.4, but the value of pt AFTER the statement completes is the address of ar[3].

Geen opmerkingen: