This preview shows pages 1–6. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Operators
Assignment: = Relational: >, >=, <, <=, ==, != Logical: &&, , ! Binary arithmetic: +, , *, /, %
% is the modulus operator: a%b is the remainder when a is divided by b e.g. 8 % 3 == 2 Shortcut assignment operators
+=, =, *=, /=, %=, etc. e.g. x += 2 // same as x = x + 2 *= 2 // same as x = x * 2 x %= 5+3 // same as x = x % (5+3) Increment/decrement operators
There are two types of increment/decrement operators
++x, x : preincrement, predecrement add or subtract 1 from x, and return the new value
x++, x : postincrement, postdecrement add or subtract 1 from x, and return the original value Example int a = 10, b, c, d; b = ++a; // a and b are now both 11 c = a++; // a is now 12, c is 11 Three ways to increment. . . Three ways to increment/decrement a variable in C
x = x + 1; x += 1; x++; Which you use is a matter of style and eciency
x++ may be slightly more ecient than x += 1 x += 1 may be slightly more ecient than x = x + 1 Order of evaluation Operator precedence and associativity rules dene the order in which operators are evaluated Some examples: 5 + 3 / 2 ≡ 5 + (3/2) 1  1  1 ≡ (1  1)  1 3 < 5 + 2 ≡ 3 < (5 + 2) Class Select Unary Binary Arithmetical Binary Arithmetical Shift Comparison Comparison Binary Bitwise Binary Bitwise Binary Bitwise Binary Boolean Binary Boolean Ternary Assignments Sequence Associativity L→R R→L L→R L→R L→R L→R L→R L→R L→R L→R L→R L→R R→L R→L L→R Operators (...) [...] > . ! ~ +  * (type) sizeof ++ */% +<< >> < <= > >= == != & ^  &&  ?...: = += + *= /= &= = ^= < <= > >=
, Avoid confusing expressions
Use parentheses to make precedence clear Q: What does this code do?
void main() { ssint a = 2, b = 1, c = 0; ssif( a < b < c ) ssssprintf( True.\n ); sselse ssssprintf( False.\n ); False.True.
ssif (a >= b >= c) ssssprintf( True.\n); sselse ssssprintf( False.\n); } ...
View Full
Document
 '08
 CRANDALL

Click to edit the document details