SlideShare a Scribd company logo
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

More Related Content

PPTX
Ch10 Program Organization
PPTX
Ch9 Functions
PPTX
Ch6 Loops
PPTX
Ch5 Selection Statements
PPTX
Ch7 Basic Types
PPT
C language Unit 2 Slides, UPTU C language
PPTX
Ch3 Formatted Input/Output
PDF
C language
Ch10 Program Organization
Ch9 Functions
Ch6 Loops
Ch5 Selection Statements
Ch7 Basic Types
C language Unit 2 Slides, UPTU C language
Ch3 Formatted Input/Output
C language

What's hot (19)

PPTX
Overview of C Mrs Sowmya Jyothi
PDF
Unit ii chapter 2 Decision making and Branching in C
PDF
User_Defined_Functions_ppt_slideshare.
PPSX
Complete C programming Language Course
PDF
C language for Semester Exams for Engineers
PDF
Programming in c by pkv
PPT
Structure of a C program
DOC
C notes diploma-ee-3rd-sem
PPTX
Lesson 7 io statements
PDF
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
PPTX
C language
PPTX
Introduction to C programming
PPTX
C LANGUAGE - BESTECH SOLUTIONS
PDF
C programming session3
PPS
Learn C
PPTX
C++ ppt
DOCX
Basic structure of c programming
DOCX
Chapter 3(1)
PPTX
Programming in C Basics
Overview of C Mrs Sowmya Jyothi
Unit ii chapter 2 Decision making and Branching in C
User_Defined_Functions_ppt_slideshare.
Complete C programming Language Course
C language for Semester Exams for Engineers
Programming in c by pkv
Structure of a C program
C notes diploma-ee-3rd-sem
Lesson 7 io statements
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
C language
Introduction to C programming
C LANGUAGE - BESTECH SOLUTIONS
C programming session3
Learn C
C++ ppt
Basic structure of c programming
Chapter 3(1)
Programming in C Basics
Ad

Similar to Ch4 Expressions (20)

PDF
Module2.1_Programming_Branching_and_looping.pdf
PPTX
Operators and Expressions
PPTX
Fundamentals of computers - C Programming
PDF
Coper in C
PPTX
Lecture 2 variables
PPTX
C basics
PPTX
C basics
PDF
CP c++ programing project Unit 1 intro.pdf
PDF
introduction to c programming - Topic 3.pdf
PPTX
c programming2.pptx
PPTX
IOS Swift Language 3rd tutorial
PPT
intro to c
PPSX
Chapter 07
PPT
C Introduction
PPT
C Intro.ppt
PPTX
Operator in C language
PPT
C_chap02.ppt Introduction to C Programming Language
PPTX
Lecture 05.pptx
PPTX
operator (1).pptx
PDF
c_programming.pdf
Module2.1_Programming_Branching_and_looping.pdf
Operators and Expressions
Fundamentals of computers - C Programming
Coper in C
Lecture 2 variables
C basics
C basics
CP c++ programing project Unit 1 intro.pdf
introduction to c programming - Topic 3.pdf
c programming2.pptx
IOS Swift Language 3rd tutorial
intro to c
Chapter 07
C Introduction
C Intro.ppt
Operator in C language
C_chap02.ppt Introduction to C Programming Language
Lecture 05.pptx
operator (1).pptx
c_programming.pdf
Ad

Recently uploaded (20)

PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
additive manufacturing of ss316l using mig welding
PDF
Well-logging-methods_new................
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
Geodesy 1.pptx...............................................
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
PPT on Performance Review to get promotions
PPTX
web development for engineering and engineering
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
additive manufacturing of ss316l using mig welding
Well-logging-methods_new................
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
CH1 Production IntroductoryConcepts.pptx
Internet of Things (IOT) - A guide to understanding
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Geodesy 1.pptx...............................................
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Embodied AI: Ushering in the Next Era of Intelligent Systems
Operating System & Kernel Study Guide-1 - converted.pdf
PPT on Performance Review to get promotions
web development for engineering and engineering
Lecture Notes Electrical Wiring System Components
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
R24 SURVEYING LAB MANUAL for civil enggi

Ch4 Expressions

  • 1. SC, Chen Ch4 Expressions Self Study Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
  • 2. 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
  • 3. 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. 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: 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)
  • 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 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*/
  • 10. • 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 */
  • 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 • 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
  • 14. 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
  • 15. 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
  • 16. 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) ) ) ) )
  • 17. 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
  • 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