Few weeks ago I was in the middle of a debate with my girlfriend – which is also a programmer – about the increment unary operator. The main topic was what will the following code display:
$i = 1; $i = $i++; echo $i;
I said 1, she said 2. Of course, I was right in the end. But we were having this conversation while we were heading out to meet some friends, so, inevitably, others were drawn into the debate. One of which is Costin, who posted on his blog an entry called The trials and tribulations of the C incrementer on this subject. Long story short, if you post increment a variable, this operation will take place last and its result will be poped first from the stack and in some cases will be lost (our case – read Costin’s post for more details).
Other annoying examples using the increment operator:
$i = 1;
function someFunction( $_value ) {
echo $_value;
}
someFunction( $i++ ); // will display 1
someFunction( ++$i ); // will display 2
$j = 1;
$j = ++$j;
echo $j; // will display 2
And again, the ZCE exam features this kind of questions.
C’mon, this is much too easy!
)
Not so easy it seems. I’ve made a strange observation while talking to people on this matter. Those who have an open source background say it’s really easy and give the correct answer and those that use Microsoft technologies (mainly .NET) will think about it a long time and finally give a wrong answer.
I do not want to argue with you but THIS is basic information for beginners !
Yeah, Raul, only that some of the programmers forget tiny things like these… And most of them don’t know basic computer architecture like memory stack, buffers, registers, etc.
Often I forget function names and required parameters but that’s why exists help files! It’s OK! On the other hand,increment operator is not tiny! It’s basic info! It could mess up everything!
)
And frankly we are not in the 80′s anymore to know CPU’s registers!
PS: And I forget a lot of them …
)
It’s about memory allocation. If you know how registers and stack work, you will never be wrong regarding the pre/post incrementation operators or regarding recursive functions. Btw, if you know all that (and it’s again basic information about a computer) you will write your code to be more fast on one architecture or another just by playing with the access times for memory (RAM) or registers.
It was tricky for me. I’d have been sure about the answer if the problem had been:
But, $i = $i++ really made me wonder what are the internals of the process…
It’s a pure theoretical issue. You won’t find stuff like this in real life. Hopefully…
I know it’s theoretical, but I can think of a situation where it may occur. A little typo bug in a couple of nested loops where you want to assign to a $j the value of $i then increment $i… I think I used something like this once, save for the typo