Re: $i++ problem understanding
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.php archive

Re: $i++ problem understanding

From: JDS <jeffrey@example.invalid>
Date: Wed Oct 05 2005 - 15:44:16 CEST

On Wed, 05 Oct 2005 11:26:52 +0200, Pugi! wrote:

> Can anyone help me understand this or see the logic in it ?

I know others are explaining it already, but here is my go.

++ increments an integer variable by one.

Whenever ++ is tacked onto a variable, the variable is incremented by one.
It doesn't matter if the variable is being passed into a function, is
being assigned to someting else, is in a for() loop, or is by itself.

++ can come *before* or *after* the variable, like this:

$i++

or this:

++$i

If ++ comes *before* the variable, then the statement on that line FIRST
increments the variable, and then uses that incremented value in the rest
of the statement.

If ++ comes *after* the variable, then the statement on that line first
uses the CURRENT value of the variable, and then increments the variable
at the end of the statement.

For example:

{
$a = 1;
$b = 2;
$c = $a + $b++;
}

// $c will be set to 3 and $b will be incremented to 3

This is different from this example:

{
$a = 1;
$b = 2;
$c = $a + ++$b;
}

// $b is incremented to 3 and then $c is set to 4

To use ++ unambiguously, always put it on a line by itself:

{
$a = 1;
$b = 2;
$c = $a + $b;
$b++;
}

does the same thing as

{
$a = 1;
$b = 2;
$c = $a + $b;
++$b;
}

That example is much less ambiguous than either of the first two.

later...

-- 
    JDS | jeffrey@example.invalid
        | http://www.newtnotes.com
  DJMBS | http://newtnotes.com/doctor-jeff-master-brainsurgeon/
Received on Tue Oct 18 02:32:13 2005