Break larger goals in smaller increments
What will be the output of the following program?
<?php function cpp(&$c) { return $c++; } cpp($c); echo cpp($c); ?>
A:
B: 1
C: 2
D: An error
Answer
This one is a little pest. Let's go through it line by line.
First there is the function which is a bug by itself. It takes the argument $c
as a reference so the changes it makes to this variable will be made to the that actual variable what was passed and not to a local copy of the variable.
What the function does at line 4 is rather interesting. It is incrementing the value of $c
but because this is a post-increment it is doing so after the value was returned.
So the original given value of $c
was returned before it was incremented. But that doesn't mean it's not going to happen (*) and because $c
is a reference the increment will be applied to actual variable passed.
When calling the function at line 7 with the uninitialized variable $c
the PHP will assume a value of NULL
. Although hidden as an argument passed to a function this still is a variable declaration. When you refer to $c
later on in the code (while still in the same scope) you will be referring to the variable $c
that was created on line 4.
As said before the function call at line 7 will return the given value of $c
(NULL
) but that is not used. But more important, it will increment $c
. PHP will consider it an integer with value so the value will become 1.
So at line 8 (that's right no code: therefore we need some whitespace in code sometimes ;) ) the value of $c
which was declared at line 7 is 1.
At line 9 it is all happening again: the function returns the given value and the given variable is incremented afterwards. Because $c
has the value 1 when entering the function 1 will also be echoed to the screen. Therefore answer B is correct.
And for completeness: at line 10 the value of $c
will be 2.
(*) Note that it's actually quite rare that code will be executed after a return statement.