Tom Kelliher, CS18
February 7, 1996
(Finishing from last time)
Arbitrary nesting possible
Example:
i = j = 0; for (i = 0; i < 10; i++) { cout << setw(10) << i << j << endl; // first 12 values printed? for (j = 9; j >= 0; j--) cout << setw(10) << i << j << endl; }
How could we break out of both loops in last example?
Includes:
Comma ( ,) binary operator:
for (sum = 0, i = 0; i < MAX; i++) sum += data[i]; cout << sum << endl;
Not the comma separating items in a list (arguments, identifiers in a declaration)
Conditional ( ? :) trinary operator:
max = (i > j) ? i : j; // condition parenthesized by conventionEquivalent to:
if (i > j) max = i; else max = j;
Another example:
cout << i << "item" << ((i > 0) ? "s" : "") << endl;
Why the parentheses around the entire conditional operator?
Assignment, being an operator, yields a value
All sequential statements (excepting void functions) have/return a value, usually discarded
Consider:
i = j = 0; i = (j = 5) + 6; if ((objectPointer = (object*) malloc(sizeof(object)) == NULL) fatal("Memory allocation failure");
Affected by:
Assignment, unary operators right associate; all others left associate
Parentheses change the order of evaluation
2 / 5 is 0. Why??? Overloading.
How can we fix it?
What is the type of 2.5 + 3?
How could we fix this:
int i = 2; int j = 5; float x; x = 2 / 5; // x == 0.0
In a mixed-type expression, how should we convert types?