开发者

Why 1 + decrementing the value + 1 = 2?

开发者 https://www.devze.com 2023-04-13 05:04 出处:网络
I found a piece of code (from one of our developer) and I was wonderin开发者_开发知识库g why the output of this is 2?

I found a piece of code (from one of our developer) and I was wonderin开发者_开发知识库g why the output of this is 2?

<?php
  $a = 1;
  $a = $a-- +1;
  echo $a;

thanks


I'll give my explanation a whirl. We're talking about a variable referencing some value off in the system.

So when you define $a = 1, you are pointing the variable $a to a value 1 that's off in memory somewhere.

With the second line, you are doing $a = $a-- + 1 so you are creating a new value and setting that to $a. The $a-- retrieves the value of the original $a, which is 1 and adds 1 to make 2 and creates that value somewhere else in memory. So now you have a variable $a which points to 2 and some other value 1 off in memory which along the way decremented to 0, but nothing is pointing at it anymore, so who cares.

Then you echo $a which points to your value of 2.

Edit: Testing Page


$a-- decrements the value after the line executes. To get an answer of 1, you would change it to --$a

<?php
 $a = 1;
 $a = --$a +1; // Decrement line
 echo $a;
?>


What the?

Just to clarify the other answers, what you have going on in this line:

 $a = $a-- +1;

Basically when PHP evaluates $a--, it actually returns the value of $a, and then runs the operation of decrementing it.

Try this

$a = 1;    
echo $a--; //outputs 1;
echo $a;  //outputs 0;

When you run this code, you will see that the number only decrements after it has been returned. So using this logic, it's a bit more clear why

echo $a-- + 1;

would output 2 instead of 1.

A better way

Perhaps a better way, arguably more clear would be

$a = $a -1 + 1


$a = 1; /* $a is 1 */
$a = ($a--) /* returns 1 and decrements the copy of $a */ + 1 /* 1 + 1 = 2 */;
echo $a; /* 2 */

The above is equivalent to something like:

$a = 1;         /* $a is 1 */
$temp = $a + 1; /* 1 ($a) + 1 = 2 */ 
$a = $a - 1;    /* decrements $a */
$a = $temp;     /* assigns the result of the above operation to $a */
echo $a;

That actually pretty much what PHP translates that into, behind the scenes. So $a-- is not such a useful operation, since $a is going to be overwritten anyway. Better simply replace that with $a - 1, to make it both clearer and to eliminate the extra operation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号