00001 #include "MusimatTutorial.h" 00002 MusimatTutorialSection(B0112) { 00003 Print("*** B.1.12 Operator Precedence and Associativity ***"); 00004 /***************************************************************************** 00005 00006 B.1.12 Operator Precedence and Associativity 00007 00008 In the expression a * x + b * y, what is the order in which the operations are carried out? By 00009 the standard rules of mathematics, we should first form the products a*x and b*y, then 00010 sum the result. So multiplication has higher precedence than addition. The natural precedence of 00011 operations can be overridden by the use of parentheses. For example, a * (x + b) * y forces the 00012 summation to occur before the multiplications. 00013 00014 In the expression a + b + c, we first add a to b, then add the result to c, so the associativity 00015 of addition is left to right. We could express left-to-right associativity explicitly like this: 00016 (((a) + b) + c). 00017 00018 The rules of precedence and associativity in programming languages can be complicated, but 00019 the programming examples in this section use the following simplified rules. 00020 00021 Expressions are evaluated from left to right, except 00022 00023 o Multiplications and divisions are performed before additions and subtractions. 00024 00025 o All arithmetic operations (+, -, *, /) are performed before logical operations (And, Or, 00026 ==, <, >). 00027 00028 o Parentheses override the above precedence rules. 00029 00030 For details, see section B.3. 00031 00032 *****************************************************************************/ 00033 00034 Integer a = 2, x = 3, b = 4, y = 5; 00035 Print("a * x + b * y = ", a * x + b * y); // prints 26 00036 Print("a * (x + b) * y = ", a * (x + b) * y); // prints 70 00037 00038 } 00039 00041 /* $Revision: 1.2 $ $Date: 2006/09/05 06:32:25 $ $Author: dgl $ $Name: $ $Id: B0112.cpp,v 1.2 2006/09/05 06:32:25 dgl Exp $ */ 00042 // The Musimat Tutorial © 2006 Gareth Loy 00043 // Derived from Chapter 9 and Appendix B of "Musimathics Vol. 1" © 2006 Gareth Loy 00044 // and published exclusively by The MIT Press. 00045 // This program is released WITHOUT ANY WARRANTY; without even the implied 00046 // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 00047 // For information on usage and redistribution, and for a DISCLAIMER OF ALL 00048 // WARRANTIES, see the file, "LICENSE.txt," in this distribution. 00049 // "Musimathics" is available here: http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=10916 00050 // Gareth Loy's Musimathics website: http://www.musimathics.com/ 00051 // The Musimat website: http://www.musimat.com/ 00052 // This program is released under the terms of the GNU General Public License 00053 // available here: http://www.gnu.org/licenses/gpl.txt 00054