Pre and post increment / decrement operators

June 21, 2019
I try to bend the internet to my will.
Wizard 22 posts
Followers: 19 people
0

Pre and post increment / decrement operators

I try to bend the internet to my will.
Wizard 22 posts
Followers: 19 people
June 21, 2019

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:

https://cffiddle.org/app/file?filepath=c0bf0e42-7a2f-475b-b40e-544edc27f16f/fc0e2db2-45ab-4008-9360-dbb4d9895f83/de304850-9816-436a-8d8b-f304532aee25.cfm

Comments (0)
Add your comment