|
Posted by Chung Leong on 10/13/78 11:28
Pugi! wrote:
> Currently I am studying PHP.
>
> I can understand the following :
> $a = 10;
> $b = $a++;
> print("$a, $b");
> will print 11, 10 on the screen.
> because when $b = $a++ first thing that happens is $b = $a
> and then $a = $a + 1. I am willing to and can accept that.
I wouldn't try to understand the sublety of the post increment
operator. It really has no reason to exist other than the fact that its
syntax was modeled after that of C, a language that's much closer to
machine code. You wouldn't really see the logic behind it unless you
understand how a CPU works.
Post-increment means you use the value of a variable, then increment
it. This happens quite often in low-level programming. For example, to
compare two strings, you'd want to tell the CPU to compare the byte at
memory address A with the byte at memory address B, then increment A
and B, so that they point to the following pair of characters for the
next comparison. Instead sending three instructions--compare,
increment, increment--to a CPU like x86 you send just one--the "scan
string" instruction. This short-hand thus speed up the operation three
times.
In any event, the reason print($i++) yields 1 is because parentheses
don't actually do anything. They are only used for resolving
precedence. The post-increment occurs right after the variable is
read--after the print operation in this case.
Another example to consider is print ($i++ + $++). This'd be the
sequence of events:
1. To perform the addition operation, A + B, PHP reads $i (which is 1)
for A
2. PHP increment $i
3. PHP reads $i (which is now 2) for B
4. PHP increment $i again
5. PHP passes the result of A + B to print, which is 3
So you see, post increment isn't the last thing that happens. It
happens right after the variable is read.
[Back to original message]
|