The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Programming Languages and Tools:
CS:3210:0001
Lecture/Lab #6
Programming with C++
Arithmetic (cont.), signed vs unsigned, bitwise operators, precedence and associativity
Warm-up
-
Name a couple of categories of compilation errors in C++
-
Is there a semantic difference between line #1 and line #2?
void calc_n( int i ) {
i * i;
}
int main() {
auto n = calc_n( 42 );
}
What's the type of variable `n` in the program below?
int i = 42;
int i = { 42 };
Arithmetic
Arithmetic operators
x + y // plus
+x // unary plus
x − y // minus
−x // unary minus
x * y // multiply
x / y // divide
x % y // remainder (modulus),
// ints only
Comparison operators
x == y // equal
x != y // not equal
x < y // less than
x > y // greater than
x <= y // less than or equal
x >= y // greater than
// or equal
Logical operators
x && y // logical and
x || y // logical or
!x // logical not
// (negation)
Bitwise operators (ints only)
x & y // bitwise and
x | y // bitwise or
x ^ y // bitwise xor
~x // bitwise complement
x << y // left shift
x >> y // right shift
Signed vs unsigned
-
A signed integer reserves its most significant bit a sign bit, representing the number's sign
-
If the sign bit is 0, the number is non-negative (positive or zero); if the sign bit is 1 then the number is negative
-
An unsigned integer uses all of its bits to represent the number's value
-
For example, an unsigned 32-bit integer has a range of 0 to 2^32-1 = 0 to 4,294,967,295 or about 4 billion
-
A signed 32-bit integer can represent numbers from -2^31-1 to 2^31, which is –2,147,483,648 to 2,147,483,647 or about -2 billion to +2 billion
7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
Precedence and Associativity
-
Precedence defines the order in which different operators in an expression are grouped. Operators with higher precedence are grouped more tightly than operators with lower precedence.
-
Associativity determines how operators with the same precedence are grouped. Operators can be either right associative (operators are grouped from right to left) or left associative (operators are grouped from left to right).
-
Together, precedence and associativity determine which parts of the expression are the operands for each of the operators in the expression.
-
We can use parenthesis to override the default rules.
Exercise 1
Use parentheses to regroup provided expressions to make the asserts pass
-
Open the exercise template
-
Write your code, press Run to test
-
When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)
-
Click on the corresponding option in the "Lab6 exercises" poll in #general
Programming with C++, Spring 2020, Lecture #6
By Aleksey Gurtovoy
Programming with C++, Spring 2020, Lecture #6
Arithmetic (cont.), signed vs unsigned, bitwise operators, precedence and associativity
- 524