int x, y = 5, z; z = 10; // assignment operator (binary) x = y + z; // addition (binary operator) x = -y; // -y is a unary operation (negation) x++; // unary (increment)
x = a + b + c - d + e; // cascading arithmetic operators x = y = z = 3; // cascading assignment operatorsThis works because the result of one operation sends back the answer (i.e. a return value) in its place, to be used in the next piece of the statement. In the above, (a + b) happens first, then the answer becomes the first operand in the next + operation.
x = a + b * c; // b * c happens first, since * has higher // precedence than +
variable_name = expression
x = 5; y = 10.3; z = x + y; // right side can be an expression a + 3 = b; // ILLEGAL! Left side must be a storage location
x = y = z = 5; // z = 5 evaluated first, returns z
int x, y; x = 5843; y = -1234; // assigning integers to int variables double a, b; a = 12.98; b = -345.8; // can assign decimal numbers to float types char letter, symb; letter = 'Z'; symb = '$'; // can assign character literals to char types bool flag; flag = true; flag = false; // can assign true or false to bool variables
Name | Symbol | Arity | Usage |
---|---|---|---|
Add | + | binary | x + y |
Subtract | - | binary | x - y |
Multiply | * | binary | x * y |
Divide | / | binary | x / y |
Modulus | % | binary | x % y |
Minus | - | unary | -x |
double x = 19.0, y = 5.0, z; z = x / y; // z is now 3.8
int x = 19, y = 5, q, r; q = x / y; // q is 3 r = x % y; // r is 4
int x = 5; float y = 3.6; z = x + y; // what does z need to be? x + y returns a float.
z = a - b * -c + d / (e - f); // 7 operators in this statementWhat order are they evaluated in?
Example of basic arithmetic
operations
v += e; means v = v + e; v -= e; means v = v - e; v *= e; means v = v * e; v /= e; means v = v / e; v %= e; means v = v % e;
++x; // pre-increment (returns reference to new x) x++; // post-increment (returns value of old x) // shortcuts for x = x + 1 --x; // pre-decrement x--; // post-decrement // shortcuts for x = x - 1
x++; ++x;
int x = 5, count = 7; result = x * ++count; // result = 40, count = 8 int x = 5, count = 7; result = x * count++; // result = 35, count = 8
char -> short -> int -> long -> float -> double -> long double
int i1, i2; double d1, d2; char c1; unsigned int u1; d1 = i1; // legal. c1 = i1; // illegal. trying to stuff int into char (usually 1 byte) i1 = d1; // illegal. Might lose decimal point data. i1 = c1; // legal u1 = i1; // dangerous (possibly no warning) d2 = d1 + i2; // result of double + int is a double d2 = d1 / i2; // floating point division (at least one operand a float type)
c1 = (char)i2; // cast a copy of the value of i2 as a char, and assign to c1 i1 = (int)d2; // cast a copy of the value of d2 as an int, and assign to i1
c1 = static_cast<char>(i2); i1 = static_cast<int>(d2);