Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Operators and
Expressions
PROGRAMMING IN ANSI C
10/03/15
Operators
Arithmetic
Relational
<
<=
>
Logical
&&
||
Bitwise
<<
>>
Assignment
++
>=
==
!=
--
&
Comma
Conditional
?:
Arrow
->
Pointer
Array element
[]
others
() - .
&
10/03/15
Expressions
10/03/15
2.
3.
4.
5.
10/03/15
3+2 +3.5
-5 % 2e.g.
= - 1 3-2 -3.5
- Subtraction or unary minus
5 % -2 = 1
* Multiplication
e.g. 3*2 3.5*2
-5 % -2 = - 1
/ Division
e.g. 3/2 3.5/2
5%1= 0
5 % 2 e.g.
= 1
% Modulo division
e.g. 5%2
5 /= -1 2.0 = - 2.5
10/03/15
+-*/%
Precedence:
10/03/15
Notice
If
be an integer.
If
10/03/15
10/03/15
2.
3.
10/03/15
a = 1/3.0;
b = a * 3.0;
5.
6.
10
10/03/15
<
<=
>
>=
==
Precedence <
<=
!=
>
!=
10/03/15
2.
3.
4.
d = a > b d=1
5.
12
10/03/15
Notice
Avoid
e.g.
/*not always 1 */
int a = 3, b = 2;
a = b == a;
/* a = 0 */
13
10/03/15
&&
||
relational operators
Associativity
a
! Right to left
&& , ||: Left to right
!a
a&&b
a||b
Value
1(True)
0 of logical
0 Expression:
1
0 & 0(False)
0
0
1
1
0
1
Operands: 0 denotes false, others denote true.
1
0
0
0
1
e.g. 3.0 && 0
1
1
0
1
1
14
10/03/15
1.
!a
2.
a&&b
4 && 5 => 1
3.
a||b
4 || 5 => 1
4.
!a||b
0 || 5 => 1
5.
4&&0||2
6.
7.
'c'&&'d'
,
0 || 2 => 1
99 || 100 => 1
15
10/03/15
16
10/03/15
Short-circuit
When
a||b
10/03/15
Associativity
Right to left
a = b = 5;
int a = b = 5;
Wrong!
int a = 5, b = 5; Right!
18
10/03/15
2.
a = b = c = 5;
c = 5, b = c, a = b
a = 5 + (c=6);
c = 6, a = 5+c
3.
/*a=11, c=6*/
a = (b=4) + (c=6);
b = 4, c = 6, a = b+c
19
10/03/15
is equivalent to:
variable = variable op expression
e.g.
x * = y + 1;
is equivalent to:
x = x * (y + 1);
20
10/03/15
a += a = 4
a += (a = a 4)
a += (a = -2)
a += a
a = (-2) + (-2) a = -4
a=a+a
21
10/03/15
++ -m ++; or
is equivalent to:
m --;
is equivalent to:
++ m;
(10 / m) ++
Wrong!
10 / m ++
Right!
m = m + 1;
or
-- m;
m = m - 1;
Associativity
Right to left
22
10/03/15
23
10/03/15
j=3; k=++j;
j=j+1; k=j;
2.
j=3; k=j++;
k=j; j=j+1;
3.
j=3; printf("%d",++j);
j=j+1; printf();
output:4
4.
printf(); j=j+1;
j=3; printf("%d",j++);
output:3
5.
6.
10/03/15
Notice
The
25
10/03/15
Associativity
Left to right
26
10/03/15
a = 3*4, 5*2 ; a = 12
2.
3.
27
10/03/15
long double
double
float
unsigned long
long
unsigned int
int
short & char
28
10/03/15
During assignment:
1.
2.
3.
10/03/15
L / i
double d; long L;
+
d;
long
float
double
Notice: in the whole process of type conversion,
only the type
of the interim value used in
float
evaluation is converted, but all the types of
variables are not converted. float
double
Except the variable x assigned
a value, all the
values of other variables are not changed.
int
double
30
10/03/15
10/03/15
Homework
Programming Exercises
32