








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A series of lecture notes from a computer science 192 class during the fall 2011 semester. The notes cover various topics related to arithmetic operators, operator precedence, type conversions, and relational & logical operators in c++ programming. Examples, explanations, and code snippets to help students understand these concepts.
Typology: Slides
1 / 14
This page cannot be seen from the preview
Don't miss anything!









Lecture 07
1
October 5, 2011Ghufran Ahmed
Lecture 07
2
-^
Increment and decrement operators
-^
x = x + 1;
Or
++x;
Or
x++;
(Prefix and postfix)
-^
x = x – 1;
Or
--x;
Or
x--;
-^
SubtletiesExample:
int x=5, y=5;cout << x++ << endl;cout << ++y << endl;cout << x << ‘,’ << y;
-^
x = 10;y = ++x;
-^
x = 10;y = x++;
Lecture 07
4
Precedence:
If two operators apply to same
operand, higher precedence operator appliedfirste.g. (3 + 5 * 6) has value 33
-^
Associativity:
If two operators have same
precedence, associate L-R or R-L as definede.g. (120 / 6 * 5) has value 100 as associatefrom L-R
Lecture 07
5
Precedence of Arithmetic and
Assignment Operators
Precedence
Operator
Associativity
1
Parentheses:
( )
Innermost first
2
Unary operators^ ++ --+ -
(unary)
Right to left
3
Binary operators *** / %**
Left to right
4
Binary operators + -
Left to right
5
Assignment operators *= += -= = /= %=
Right to left
Lecture 07
7
-^
Type converted to that of the receiving variable float
tree
=
3;
//int
to
float
int
guess
=
3.9832;
//float
to
int
int
debt
=
3.0E12;
//erroneous
-^
What output if we
cout tree
,^
guess
and
debt
?
-^
Potential problems: Loss of precision, or loss offractional part, or out of range. Compilercomplains usually
Lecture 07
8
the specified type (as opposed to automaticconversions)
(type) expression
or
type (expression)
e.g.
(float) 5/2; char(77);
long (shorty); int (‘Z’);
Lecture 07
10
connecting
true
and
false
values
is
bool
(true or false)
expressions of any data type that can becompared
true
, zero to
false
Lecture 07
11
-^
Fill table of (p AND q), (p OR q), (NOT p). Also for 3variables. Precedence lower than arithmetic operators #include <iostream.h>int main(){
int p, q;cout << "Enter P (0 or 1): ";cin >> p;cout << "Enter Q (0 or 1): ";cin >> q;cout << "P AND Q: " << (p && q) << endl;cout << "P OR Q: " << (p || q) << endl;return 0; }
Lecture 07
13
may be legal C++ code but will not do whatyou (for now) expect them to do if (x < y < z)
// WRONG!
cout << "y is between x and z“ << endl;
cout << "y is between x and z" << endl;
Lecture 07
14
sizeof
operator to test sizes
e.g.
cout << sizeof(int);cout << sizeof i; //i is a variable