The difference between the pre and post increment and decrement operators
In the excellent CFML News from Foundeo Inc there was a link to
Compound Assignment Operators in CFML ( += and more) on Matthew Clemente’s blog. One of the examples Matthew shows is the value++
and value--
shorthand you can use for incrementing / decrementing numeric values. I thought I’d post that there is also ++value
and --value
. So what’s the difference?
Here’s a quick test:
value = 10; value++; writeDump(value); // 11 value--; writeDump(value); // 10 value = 10; ++value; writeDump(value); // 11 --value; writeDump(value); // 10
Hmmm, so we got exactly the same output. The difference between them is quite subtle but worth knowing. Consider the following:
i = 10; result = []; while(i++ < 15) { result.append(i); } writeDump(result); // [11,12,13,14,15] i = 10; result = []; while(++i < 15) { result.append(i); } writeDump(result); // [11,12,13,14]
In the first example, it iterates five times, in the second example it iterates four times.
What is happening is that in the i++
version it post increments and in the ++i
version it pre increments.
This should make it clearer.
foo = 10; bar = foo++; writeDump(foo); // 11 writeDump(bar); // 10 foo = 10; bar = ++foo; writeDump(foo); // 11 writeDump(bar); // 11
As you can see, when it assigns the value to bar
in the foo++
version, it increments the value after it assigns it to bar
. So bar
has a value of 10.
When it assigns the value to bar
in the ++foo
version, it increments the value before it assigns it to bar
. So bar
has a value of 11.
I’ve used both pre and post versions. Digging around for a real world example of the pre increment version, I found that DI/1 uses it.
https://github.com/framework-one/fw1/blob/develop/framework/ioc.cfc#L31
Here’s the examples above on cffiddle: