APS105 L04 - Arithmetic

#APS105 Slides Lecture Link to web notes
Arithmetic in C follows BEDMAS and is left-associative (left to right).

Division of integers

Modulo (%)

Rule of thumb for C
If we can represent a/b then (a/b) * b + (a%b) = a.
We can't represent a/b itself, because if b=0, then a/b is division by 0.
However, in C, we can do it, but it is undefined.
Running it each time will return a different number.
This is known as Undefined Behavior.

Mixing types
If both operators are int, the result is still an int.
If at least one operator is a double, then the result get's converted to a double automatically.

Mixing doubles and integers
The result of an operation using integers will still be an integer, even if the variable assignment is to a double.

Explicit type conversion
Where we specifically request a type conversion. It uses a type cast, which is a unary operator with form (type) value.

(int) 2.9 gets truncated to 2.
(double) 5/2 gets computed as ((double) 5) / 2
(double) (int) 2.9 gets computed as ((double) ((int) 2.9))

Assignment is a binary operator
e.g. x=3 results in a 3.
Not recommended by Jon Eyolfson

Shorthand
x *= 2 is the same as x = x * 2.
++x is incrementing x (increasing by one).
--x is decrementing x (decreasing by one).
Note that x++ and x-- does not work?
Or maybe it does? Just not recommended.

sizeof is a unary operator that returns the number of bytes that a variable or type uses.

sizeof(int); //returns 4
sizeof(double); // returns 8
sizeof(char); // returns 1
sizeof(bool); // returns 1

double x = 2.0;
sizeof(x); // returns 8