The fabric of a program consists of expressions, large and small, stitched together with operators and interspersed with functions. The larger expressions as well as the functions themselves may be the result of development from a number of smaller expressions. An understanding of the operators and their correct usage is therefore very essential. This tutorial describes the various operators by presenting comprehensive examples of their usage tested on the MX 6.1 server. <CFScript> will be used in all the examples.
What You Must Know About Operators in ColdFusion! (Page 1 of 4 )
ColdFusion like other programming languages has many operators of the following basic types:
Examples & Comments
+, -, *, /
Basic add, subtract, multiply and divide (the right hand operand cannot be zero)
Add: #x# + #y#
Subtract: #x# - #y#
Multiply: #x# * #y#(x*y = y*x)
Divide: #x# / #y#
Used just to change the sign of variable. i.e, to change 5 to -5
-#x# ( to get a negative of x).
Remainder left after a division
Example: 5 mod 2 is 1
Sign of modulus is sign of dividend
The right operand cannot be zero
^ : the Caret
Exponentiation (raising the power)
Example: #x# ^ 2(exponent is 2)
The exponent can be floating point, negative
Represents integer division
Example: #x# #z#
For floating point numbers the integer part is used.
Examples using arithmetic operators
The following example shows several of the operators and their usage.
<!--- Arithmetic Operators --->
<!--- Author: Jay Krishnaswamy --->
writeoutput("There are " & #apples# & " Apples <br/>");
writeoutput("There are " & #oranges# & " Oranges<br/>");
writeoutput("There are " & #bananas# & " bananas<br/><hr width='40%''
//Inside <cfscript/> use double slash for comments
WriteOutput("Total of apples and bananas = " & #apples#+#bananas# );
WriteOutput("How many more oranges than apples?: " & # oranges#-#apples#);
WriteOutput("3 times the number of apples are " & 3*#apples# & " apples");
WriteOutput("Half the number of oranges are " & #oranges# /2 & " oranges");
WriteOutput("5 divided by 0 is:" );
WriteOutput( 5/0 & "<br/>");
<cfset .../> tags and <cfoutput> ..... </cfoutput> tags can also be used, but you may have to write a lot of such tags for the example shown.
The following picture shows the display when browsed with FireFox. It appears that FireFox can display the resulting html up to the line which has the error, but IE 6.0 just gives an HTTP 500 error. For displaying in IE 6.0, the last line needs to be modified.