rfg@pink.ACA.MCC.COM (Ron Guilmette) (05/27/89)
Consider the following short program. In what order should the addition operations in "main" be performed? Does the language definition insist on any particular ordering for these addition operations? If so, what is the required order? For this example, the ordering of evaluation of the sums makes no difference to the result, but you can easily imagine cases where the ordering *would* make a difference (such as the case where one or more of the sums were formed from sub-expressions which themsleves produce side-effects... WARNING: don't try this at home :-). The results I get for this example program (with G++) are somewhat surprizing (to me at least). Since G++ evaluates arguments in right to left order, the rightmost addition is performed first, even though (or perhaps because) the associativity of the << operator is left-to- right. class base { public: base (int i) { } base& operator<< (int i) { printf ("%d\n", i); } }; int v1 = 7, v2 = 9, v3 = 5, v4 = 3, v5 = 0, v6 = 0; int main () { base base_object(1); base_object << (v1+v2) << (v3+v4) << (v5+v6); return 0; } -- // Ron Guilmette - MCC - Experimental Systems Kit Project // 3500 West Balcones Center Drive, Austin, TX 78759 - (512)338-3740 // ARPA: rfg@mcc.com // UUCP: {rutgers,uunet,gatech,ames,pyramid}!cs.utexas.edu!pp!rfg
jss@hector.UUCP (Jerry Schwarz) (05/27/89)
In article <224@pink.ACA.MCC.COM> rfg@MCC.COM (Ron Guilmette) writes: >Consider the following short program. In what order should >the addition operations in "main" be performed? > >Does the language definition insist on any particular ordering >for these addition operations? If so, what is the required order? > C++, like C, does not in general (there are some well defined exceptions) specify the order of evaluation of subexpressions or of argument lists. This is intended to provide the compiler with flexibility to choose an efficient ordering. In cases where subexpressions have side effects and order matters you must write the code to explicitly force your desired order. Jerry Schwarz AT&T Bell Labs, Murray Hill