SC, Chen
Ch4 Expressions
Self Study Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
Ch4 Expressions
• One of C’s distinguishing characteristics: Emphasis on expressions
• The simplest expressions: variables and constants
Variable: represent a value to be compute as the program runs
Constants: represent a value that doesn’t change
• More complicated expressions: operators to operands
Operator: basic tools for building expression
Arithmetic operators, Relational operators, Logical operators, …and so on
Ch4 Expressions
4.1 Arithmetic Operators
4.2 Assignment Operators
4.3 Increment and Decrement Operators
4.4 Expression Evaluation
4.5 Expression Statements
4.1 Arithmetic Operators (1/2)
Unary Binary
+ unary plus
- unary minus
Additive Multiplicative
+ addition
- subtraction
* multiplication
/ division
% remainder
Require one operand
*The unary + operator
does nothing and is not
exist in K&R C.
Require two operands
[Using Mixed Operands]
• Except %, allow either integer or floating-point operands, with mixing
allowed.
• When int and float operands are mixed, the result has type float.
4.1 Arithmetic Operators (2/2)
[Special require care for / and % operators]
*For / operator
The / operator will truncate the result by dropping
the fractional part when bot of its operands are int.
*For % operator
The % operator requires int operands.
*For both / and % operators
1. Will cause undefined behavior when using zero
as the right operand.
2. It is tricky that describe the result when / and %
are used with negative operands
C98 C99
/
The result of a division can be rounded either up or down
Ex: -9 / 7 can be -1 or -2 The result of a division is always truncated toward zero.
Ex: -9 / 7 is -1
Ex: -9 % 7 is -2%
If one of operand is negative, the sign of result depends
on the implementation
Ex: -9 % 7 can be -2 or 5
Undefined
Behavior
Ch4.4
[Implementation-Defined Behavior]
• The C standard deliberately leaves parts of the
language unspecified.
• The program may vary somewhat from one
implementation to another due to various
definitions for the unspecified details.
• The implementation-defined behavior needed
to be documented.
• It is best to avoid writing programs that depend
on implementation-defined behavior.
4.1 Arithmetic Operators:
Operator Precedence and Associativity
1. Parentheses for grouping in all expressions
2. Operator precedence rules
• Compiler will interpret the expression by
repeatedly putting parentheses around
subexpressions, starting with high-precedence
operators and working down to low-precedence
operators
3. Associativity
1) Left-associativity
• Binary arithmetic operators (*, /, %, +, and -)
2) Right-associativity
• Unary arithmetic operators (+ and -)
Table of
Operators
Appendix A
Highest + - (unary)
* / &
Lowest + - (binary)
Before After
i + j * k i + (j * k)
-i * -j (-i) * (-j)
+i + j / k (+i) + (j / k)
i - j - k (i – j) – k
i * j / k (i * j) / k
- + i - (+ I)
4.1 Arithmetic Operators
4.2 Assignment Operators
• Simple assignment
When program need to store the computed value in a variable for later use, C
uses the = operator.
• Compound assignment
For updating a value already stored in a variable
Chained assignments
with type conversion
4.2 Assignment Operators: Simple Assignment (1/2)
• v = e
Evaluate the expression e and copy its value into v
e can be a constant, a variable, or a more complicated expression
If v and e don’t have the same type
− The value of e is converted to the type of v as the assignment takes place
• Assignment
In many other programming languages: is a statement
In C: is an operator -> The act of assignment produces a result
− The value of an assignment v = e is the value of v after assignment
− Several assignments can be chained together
− The = operator is right associative
Conversion
during
assignment
Ch 7.4
int i ;
i = 72.99f /* i is now 72*/
i = j = k = 0;
i = (j = (k = 0));
int i ;
float f;
f = i = 33.3f /* f is 33.0*/
• Operators with side effects
Most C operators don’t modify their operands, but some do
Do more than just compute a value
The simple assignment operator is the first operator we’ve seen that has side
effects
− It modifies its left operand
• Embedded assignments
An assignment of the form v = e is allowed wherever a value of type v would
be permitted
Make program hard to read
A source of subtle bugs
4.2 Assignment Operators: Simple Assignment (2/2)
Expression
Evaluation
Ch 4.4
i = 1;
k = 1 + ( j = i );
printf ( “%d %d %dn”, i, j, k ) ; /* prints “1 1 2” */
i = 0; /* Produce the result 0 and the side
effect is to assign 0 to i */
4.2 Assignment Operators: lvalues
• v = e
e can be a constant, a variable, or a more complicated expression
The assignment operator requires an lvalue as its left operand
• lvalue
An object stored in computer memory
− Variables
− Other kinds of lvalue will appear in later chapters
Not constant or the result of a computation
− Expressions
•The compiler will detect errors of this nature
Invalid lvalue in assignment
12 = i; /* WRONG*/
i + j = 0; /* WRONG*/
-i = j; /* WRONG*/
rvalue, but use the term “expression” instead
4.2 Assignment Operators: Compound Assignment
• Use the old value of a variable to compute its new value
• Allow to shorten this statement
9 other compound assignment operators:
− -=, *-, /=, %=, and so on
All compound assignment operators work in much the same way
Be careful not to switch the two characters of compound operators
− Will pass the compiler, but get the different meaning
• Compound operators have the same properties as the = operator
Right associative
i = i + 2;
i += 2;
Other assignment operators
Ch 20.1
Those two are just equivalent, there are still some cases where those two may not be the same:
1. Operator precedence
2. v itself has a side effect
i *= j + k;
i += j += k;
i += (j += k);
Side Effect
• Evaluating v += e causes v to be evaluated only once
• Evaluating v = v + e causes v to be evaluated twice
a[i++] += 2;
a[i++] = a[i++] + 2;
The effect of executing the statement is undefined
4.3 Increment and Decrement Operators
• Symbol
1. Increment: ++
2. Decrement: --
• Complications:
1. Prefix & Postfix
a. Prefix
b. Postfix
2. Side effect
Modify the values of their operands
• Use more than once in the
same expression, the result can
often be hard to understand
i = 1;
printf(“i is %dn”, ++i); /* prints “i is 2” */
printf(“i is %dn”, i); /* prints “i is 2” */
i = 1;
printf(“i is %dn”, i++); /* prints “i is 1” */
printf(“i is %dn”, i); /* prints “i is 2” */
i = 1;
j = 2;
k = ++i + j++;
i = 1;
j = 2;
k = i++ + j++;
i = i + 1;
k = i + j;
j = j + 1;
i = i + 1;
j = j + 1;
k = i + j;
Increment i immediately
Increment i later
How long?
At least before the
next statement
Increment and Decrement Operators
• C inherited ++ and -- from Ken Thompson’s earlier B language
• These operators have become a deeply ingrained part of C
• With modern compilers, using these operators won’t make a compiled
program any smaller or faster
The continued popularity of these operators stems mostly from their brevity and
convenience
• Can be applied to floating-point numbers as well as integers
• “Sequence Point”
The end of an expression statement is one sequence point
The expression with postfix ++ or – will update the stored value of the operand shall
occur between the previous and the next sequence point
4.4 Expression Evaluation
Precedence Name Symbol(s) Associativity
1
Increment (postfix)
Decrement (postfix)
++
- -
Left
2
Increment (prefix)
Decrement (prefix)
Unary plus
Unary minus
++
- -
+
-
Right
3 Multiplicative * / % Left
4 Additive + - Left
5 Assignment = *= /= %= += -= Right
a = b += c++ - d + --e / -f
(a = (b += ( ( (c++) – d) + ( (--e) / (-f) ) ) ) )
4.4 Expression Evaluation:
Order of Subexpression Evaluation
• Can determine uniquely where the parentheses would go if the expression
were fully parenthesized by the rules of operator precedence and associativity
• However, the order of subexpression evaluation may also influence the value
of the expression
C doesn’t define this order
− Exception: subexpressions involving the logical and, logical or, conditional and comma operators
Most expressions have the same value regardless of the order in which their
subexpressions are evaluated
Here comes a problem when a subexpression modifies one of its operands
− Cause undefined behavior: Avoid writing this kind statements
Logical and and
or operators
Ch 5.1
Conditional
operator
Ch 5.2
Comma
operator
Ch 6.3
a = 5;
c = (b = a + 2) – (a = 1);
i = 2;
j = i * i++;
[Warning] operation on ‘a’ may be undefined
Registers
Ch 18.2
4.5 Expression Statements
• Any expression can be turned into a statement by appending a
semicolon
Ex:
− i is first incremented, then the new value of i is fetched
− The value of ++i is discarded and the next statement executed since ++i isn’t part of a
larger expression (The change to i is permanent)
• There is little point in using an expression as a statement unless the
expression has a side effect
++i;
Statement i = 1; i--; i * j – 1;
Action
1. 1 is stored into i
2. The new value of i is fetched
but not used
1. The value of i is fetched but
not used
2. i is decremented afterwards
1. The value of the expression is
computed and then discarded
[Warning] statement with no effect

Ch4 Expressions

  • 1.
    SC, Chen Ch4 Expressions SelfStudy Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
  • 2.
    Ch4 Expressions • Oneof C’s distinguishing characteristics: Emphasis on expressions • The simplest expressions: variables and constants Variable: represent a value to be compute as the program runs Constants: represent a value that doesn’t change • More complicated expressions: operators to operands Operator: basic tools for building expression Arithmetic operators, Relational operators, Logical operators, …and so on
  • 3.
    Ch4 Expressions 4.1 ArithmeticOperators 4.2 Assignment Operators 4.3 Increment and Decrement Operators 4.4 Expression Evaluation 4.5 Expression Statements
  • 4.
    4.1 Arithmetic Operators(1/2) Unary Binary + unary plus - unary minus Additive Multiplicative + addition - subtraction * multiplication / division % remainder Require one operand *The unary + operator does nothing and is not exist in K&R C. Require two operands [Using Mixed Operands] • Except %, allow either integer or floating-point operands, with mixing allowed. • When int and float operands are mixed, the result has type float.
  • 5.
    4.1 Arithmetic Operators(2/2) [Special require care for / and % operators] *For / operator The / operator will truncate the result by dropping the fractional part when bot of its operands are int. *For % operator The % operator requires int operands. *For both / and % operators 1. Will cause undefined behavior when using zero as the right operand. 2. It is tricky that describe the result when / and % are used with negative operands C98 C99 / The result of a division can be rounded either up or down Ex: -9 / 7 can be -1 or -2 The result of a division is always truncated toward zero. Ex: -9 / 7 is -1 Ex: -9 % 7 is -2% If one of operand is negative, the sign of result depends on the implementation Ex: -9 % 7 can be -2 or 5 Undefined Behavior Ch4.4 [Implementation-Defined Behavior] • The C standard deliberately leaves parts of the language unspecified. • The program may vary somewhat from one implementation to another due to various definitions for the unspecified details. • The implementation-defined behavior needed to be documented. • It is best to avoid writing programs that depend on implementation-defined behavior.
  • 6.
    4.1 Arithmetic Operators: OperatorPrecedence and Associativity 1. Parentheses for grouping in all expressions 2. Operator precedence rules • Compiler will interpret the expression by repeatedly putting parentheses around subexpressions, starting with high-precedence operators and working down to low-precedence operators 3. Associativity 1) Left-associativity • Binary arithmetic operators (*, /, %, +, and -) 2) Right-associativity • Unary arithmetic operators (+ and -) Table of Operators Appendix A Highest + - (unary) * / & Lowest + - (binary) Before After i + j * k i + (j * k) -i * -j (-i) * (-j) +i + j / k (+i) + (j / k) i - j - k (i – j) – k i * j / k (i * j) / k - + i - (+ I)
  • 7.
  • 8.
    4.2 Assignment Operators •Simple assignment When program need to store the computed value in a variable for later use, C uses the = operator. • Compound assignment For updating a value already stored in a variable
  • 9.
    Chained assignments with typeconversion 4.2 Assignment Operators: Simple Assignment (1/2) • v = e Evaluate the expression e and copy its value into v e can be a constant, a variable, or a more complicated expression If v and e don’t have the same type − The value of e is converted to the type of v as the assignment takes place • Assignment In many other programming languages: is a statement In C: is an operator -> The act of assignment produces a result − The value of an assignment v = e is the value of v after assignment − Several assignments can be chained together − The = operator is right associative Conversion during assignment Ch 7.4 int i ; i = 72.99f /* i is now 72*/ i = j = k = 0; i = (j = (k = 0)); int i ; float f; f = i = 33.3f /* f is 33.0*/
  • 10.
    • Operators withside effects Most C operators don’t modify their operands, but some do Do more than just compute a value The simple assignment operator is the first operator we’ve seen that has side effects − It modifies its left operand • Embedded assignments An assignment of the form v = e is allowed wherever a value of type v would be permitted Make program hard to read A source of subtle bugs 4.2 Assignment Operators: Simple Assignment (2/2) Expression Evaluation Ch 4.4 i = 1; k = 1 + ( j = i ); printf ( “%d %d %dn”, i, j, k ) ; /* prints “1 1 2” */ i = 0; /* Produce the result 0 and the side effect is to assign 0 to i */
  • 11.
    4.2 Assignment Operators:lvalues • v = e e can be a constant, a variable, or a more complicated expression The assignment operator requires an lvalue as its left operand • lvalue An object stored in computer memory − Variables − Other kinds of lvalue will appear in later chapters Not constant or the result of a computation − Expressions •The compiler will detect errors of this nature Invalid lvalue in assignment 12 = i; /* WRONG*/ i + j = 0; /* WRONG*/ -i = j; /* WRONG*/ rvalue, but use the term “expression” instead
  • 12.
    4.2 Assignment Operators:Compound Assignment • Use the old value of a variable to compute its new value • Allow to shorten this statement 9 other compound assignment operators: − -=, *-, /=, %=, and so on All compound assignment operators work in much the same way Be careful not to switch the two characters of compound operators − Will pass the compiler, but get the different meaning • Compound operators have the same properties as the = operator Right associative i = i + 2; i += 2; Other assignment operators Ch 20.1 Those two are just equivalent, there are still some cases where those two may not be the same: 1. Operator precedence 2. v itself has a side effect i *= j + k; i += j += k; i += (j += k);
  • 13.
    Side Effect • Evaluatingv += e causes v to be evaluated only once • Evaluating v = v + e causes v to be evaluated twice a[i++] += 2; a[i++] = a[i++] + 2; The effect of executing the statement is undefined
  • 14.
    4.3 Increment andDecrement Operators • Symbol 1. Increment: ++ 2. Decrement: -- • Complications: 1. Prefix & Postfix a. Prefix b. Postfix 2. Side effect Modify the values of their operands • Use more than once in the same expression, the result can often be hard to understand i = 1; printf(“i is %dn”, ++i); /* prints “i is 2” */ printf(“i is %dn”, i); /* prints “i is 2” */ i = 1; printf(“i is %dn”, i++); /* prints “i is 1” */ printf(“i is %dn”, i); /* prints “i is 2” */ i = 1; j = 2; k = ++i + j++; i = 1; j = 2; k = i++ + j++; i = i + 1; k = i + j; j = j + 1; i = i + 1; j = j + 1; k = i + j; Increment i immediately Increment i later How long? At least before the next statement
  • 15.
    Increment and DecrementOperators • C inherited ++ and -- from Ken Thompson’s earlier B language • These operators have become a deeply ingrained part of C • With modern compilers, using these operators won’t make a compiled program any smaller or faster The continued popularity of these operators stems mostly from their brevity and convenience • Can be applied to floating-point numbers as well as integers • “Sequence Point” The end of an expression statement is one sequence point The expression with postfix ++ or – will update the stored value of the operand shall occur between the previous and the next sequence point
  • 16.
    4.4 Expression Evaluation PrecedenceName Symbol(s) Associativity 1 Increment (postfix) Decrement (postfix) ++ - - Left 2 Increment (prefix) Decrement (prefix) Unary plus Unary minus ++ - - + - Right 3 Multiplicative * / % Left 4 Additive + - Left 5 Assignment = *= /= %= += -= Right a = b += c++ - d + --e / -f (a = (b += ( ( (c++) – d) + ( (--e) / (-f) ) ) ) )
  • 17.
    4.4 Expression Evaluation: Orderof Subexpression Evaluation • Can determine uniquely where the parentheses would go if the expression were fully parenthesized by the rules of operator precedence and associativity • However, the order of subexpression evaluation may also influence the value of the expression C doesn’t define this order − Exception: subexpressions involving the logical and, logical or, conditional and comma operators Most expressions have the same value regardless of the order in which their subexpressions are evaluated Here comes a problem when a subexpression modifies one of its operands − Cause undefined behavior: Avoid writing this kind statements Logical and and or operators Ch 5.1 Conditional operator Ch 5.2 Comma operator Ch 6.3 a = 5; c = (b = a + 2) – (a = 1); i = 2; j = i * i++; [Warning] operation on ‘a’ may be undefined Registers Ch 18.2
  • 18.
    4.5 Expression Statements •Any expression can be turned into a statement by appending a semicolon Ex: − i is first incremented, then the new value of i is fetched − The value of ++i is discarded and the next statement executed since ++i isn’t part of a larger expression (The change to i is permanent) • There is little point in using an expression as a statement unless the expression has a side effect ++i; Statement i = 1; i--; i * j – 1; Action 1. 1 is stored into i 2. The new value of i is fetched but not used 1. The value of i is fetched but not used 2. i is decremented afterwards 1. The value of the expression is computed and then discarded [Warning] statement with no effect

Editor's Notes

  • #7 舉例子
  • #15 The postfix versions of ++ and – have higher precedence than unary plus and minus Left associative The prefix versions of ++ and – have the same precedence than unary plus and minus Right associative