$\require{cancel}$
Integer Operations
- The operations are discussed in general here
- A unary operation only involves one number.
- A binary operation involves two numbers
- +,- and *
- Are addition, subtraction and multiplication.
- These are closed under the integers.
- Ie you add two integers, you get an integer back.
- And are, within overflow, closed on the integer types.
- / and %
- These are division and remainder.
- For the integers these are not closed.
- 7/2 = 3.5 or 3 R 1 in mathematics.
- In c++ 7/2 is integer division and is 3.
- Integer division rounds down.
- In c++ 7%2 is integer remainder and is 1.
- % is sometimes called modulus.
- Operator precedence: please excuse my dear aunt sally
- Do parenthesis first ()
- Do exponentiation next, but we put this off for a bit.
- Do multiply, divide and modulus from left to right.
- Do add and subtract from left to right.
- See The operator precedence table at cppreference.
- C had several convenience functions
- Compound assignment
- we do this all of the time :
-
var = var op expression
- Ie
a = a * 5
- As a shortcut, c and c++ have the functions
-
var op= expression
- IE
a *= 5
- This works for +, -, *, /, % and others.
- prefix/postfix increment and decrement
- We also do this all of the time:
-
i = i + 1
- So c provided the shortcuts
- There is a difference if they are used in an expression.
- The prefix operators (++i) return the old value of I then increment
- The prefix operators (i++) increment and return the new value of i.
- Take a look at intOps.cpp.
- There are more operators.
- & is bitwise and
- | is bitwise or
- ~ is bitwise not.
- << is shift left
- >> is shift right.
- See intBit.cpp.