Incrementing with ++

One of the handier recent additions to ColdFusion was the ability to use ++ and – operators. For example, to add one to x you can either do: x=x+1. Or the quicker: x++. However, don’t forget that you can also do ++x. What’s the difference? Well it’s pretty important.

When we say x++, the result of that expression would be the original value of x, before 1 is added to it. Consider:

<cfset x = 1> <cfoutput>#x++#</cfoutput>

This will print out 1 to the screen, but if you follow it up with:

<cfoutput>#x#</cfoutput>

you will see 2. In other words, the expression as a whole “worked” in that it added one to the value, but the returned value was the original value.

If you want to both add one to a value, and return the result after the addition, you would use the reverse form.

<cfset x = 1> <cfoutput>#++x#</cfoutput> <br> <cfoutput>#x#</cfoutput>

Why bring this up? I was working with the parseExcel function (just released on CFLib) and noticed it returned 2 of my Excel sheets 3 arrays. Why? This one line:

<cfset loc.numAcross = loc.cols++>

The fix was to just reverse the plus signs.

<cfset loc.numAcross = ++loc.cols>

An easy way to remember this would be to see that the + signs are first, which you can read as “plus first, then return”.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments