|
Posted by Jerry Stuckle on 10/07/05 00:06
Chung Leong wrote:
> 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.
>
Chung,
Actually, Dana is correct. "i++ + i++" is undefined in C. The language
defines the evaluation order of the operators - but not the operands.
So if i = 1, the result could be 1+1, 2+1 or 1+2 (although probably not
the last). It's up to the compiler manufacturers on how it's implemented.
Another example is func(i++, i++). This could be passed as (1,1), (1,2)
or (2,1) (again, probably not the last).
It's an example I've used quite frequently in my advanced C and C++ classes.
However - since PHP is basically written by one company and has pretty
much the same code base for all platforms, I would expect the same
version of PHP to act similarly across platforms. However, I wouldn't
want to guarantee it across versions.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================
[Back to original message]
|