SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
1
Expressions, Evaluation and Assignments
• Arithmetic expressions
• Overloaded operators
• Type conversions
• Relational and Boolean expressions
• Short-circuit evaluation
• Assignment statements
• Mixed-mode assignment statements
• Sebesta Chapter 7
2
Expressions
• Expressions are fundamental means of specifying
computations in programming languages
• Understanding how expressions are evaluated requires
knowing the order in which operator and operand are
evaluated
• Essence of imperative languages is the dominant role of
assignment statements, including expressions
3
Arithmetic Expressions
• Evaluation of numeric expressions
– Motivation for the development of PLs
• Remember trajectory tables?
• Arithmetic expressions consist of
– Operators
– Operands
– Parentheses/delimiters
– Function calls
4
Design Issues for Arithmetic Expressions
1. What are the operator precedence rules?
2. What are the operator associativity rules?
3. What is the order of operand evaluation?
4. Are there restrictions on operand evaluation side
effects?
5. Is user-defined operator overloading supported?
6. What mode mixing in expressions is allowed?
5
Arity of Arithmetic Expressions
• Arity
– Number of operands/arguments of a function
• A unary operator has one operand
• A binary operator has two operands
– Most common operators
• A ternary operator has three operands
• Some languages support N-ary operators
– In Lisp, a benefit of prefix representation
(* pi r r) vs. pi*r*r or pi*r^2
6
Operator Precedence Rules
• Precedence define the order in which adjacent operators
are evaluated
– Adjacent - separated by at most one operand
• Different PLs have different precedence levels
• Typical precedence levels – highest to lowest
1. Parentheses
2. Unary operators
3.** (exponentiation, if the language supports it)
4.*, /, % (modulo)
5.+, -
7
Operator Associativity Rules
• Define the order in which adjacent operators with the
same precedence level are evaluated
• Typical associativity rules
– Left to right, except ** which is right to left
– Unary operators may associate right to left (e.g., FORTRAN)
• APL is different
– All operators have equal precedence and
– All operators associate right to left!
• Parentheses override precedence and associativity rule
8
Expression Evaluation Process
• Order of evaluation is crucial
1. Variables
– fetch value from memory
1. Constants
– either implicit in instruction
– or fetch from memory
1. Parenthesized expressions
– evaluate all operands and operators first
1. Function references
– the most interesting
9
Functions/Procedures
Result/
Return value
Input/Output Side Effects
Function/Procedure
Arguments/
Parameters
• Parameters – pass by value (in) or by reference (in/out)
• Return value
• Input/Output
• Side Effects
10
Side Effects
• Side effect
– a function or procedure changes a two-way
parameter or a non-local variable
• A major problem with side effects:
– When a function referenced in an expression alters another
operand of the expression; e.g., for a parameter change:
a = 10;
b = a + fun(&a); /*Assume fun changes its parameter*/
• Results of the expression depend on the order of
evaluation of statements!!
– why is this bad?
11
Solution 1: Prohibit Side Effects!
1. Language definition prohibits side effects
– No two-way parameters
– No non-local references
• Advantage
– It works!
– E.g. functional languages
• Disadvantages:
– Need flexibility of two-way parameters and non-local variables
• What about C? What about Java?
– Copying of parameters to avoid side effects
12
Solution 2: Fix Evaluation Order
2. Operand evaluation order is fixed in language definition
• Advantage
– We always know how expression will be evaluated
• Disadvantage
– This limits some compiler optimizations
13
Conditional Expressions
• Ternary operator <cond> ? <expr1> : <expr2>
– Same as if (<cond> ) <expr1> else <expr2>
– C, C++, and Java <condition> average
(count == 0) ? 0 : sum / count
– Lisp:
(if <test> <do-if-true> <do-ifnot>)
• Short-circuit evaluation means
1. Evaluate test first and then
2. Evaluate only the branch taken
• e.g. avoid division by zero above
14
Overloading Operators
• Operator overloading
– use of an operator for more than one purpose
• Some are common (e.g., + for int and float)
• Some are potential trouble
• e.g., * in C and C++, / for int and float in Java
– Loss of compiler error detection
• Missing operand should be a detectable error
– Some loss of readability
– Can be avoided by introduction of new symbols
e.g., Pascal’s div
15
User-defined Overloaded Operators
• C++ and Ada allow user-defined overloaded operators
• Problems
– Users can define nonsense operations
– Readability may suffer, even when the operators make sense
16
Type Conversions
• Narrowing conversion
– converts to a “smaller” type (type has fewer values)
• e.g., float to int
• 3.99 to 4
• Widening conversion
– converts to a type that includes all values of the
original type
– or at least an approximation of each
• e.g., int to float
• 4 to 4.0f
17
Type Conversions
• Mixed-mode expression
– Operands of different types
• Coercion
– An implicit type conversion
• Disadvantage
– Decreases the type error detection ability of the compiler
• In most languages, widening conversions of numeric
types in expressions can be coerced
• In Ada, there are virtually no coercions in expressions
18
Explicit Type Conversions
• In C, C++, Ada, Java called casts
• E.g., Ada:
FLOAT (INDEX) --INDEX is INTEGER type
– converts to floating point
• E.g., Java:
float speed = 45.5;
(int) speed; /* =45; cuts off fractional part*/
19
Errors in Expressions
1. Inherent properties of mathematical functions
– e.g. division by zero, infinity
1. Approximate representations
– Fractions (e.g. 2/3, 0.1) and irrational numbers like π and e
– Approximate huge integers with floating point
1. Limitations of computer arithmetic
– e.g. overflow, underflow
• If ignored by the run-time system (may even be
undetectable) can lead to
crashes, erroneous output, unpredictable behavior
• Less of a problem in some languages!
– E.g. exact fractions and huge integers in Lisp prevent errors of
type 2 & 3
20
Relational Operators, Boolean Expressions
• Boolean data type
– 2 values
• True
• False
• Boolean expression
– Has relational operators and operands of various types
– Evaluates to a Boolean value
– Operator symbols vary among languages
• e.g.not equal
– !=
– /=
– .NE.
– <>
– #
21
Boolean Expressions
• Operands are Boolean
• Result is Boolean
Boolean operator comparison
F77 FORTRAN 90 C Ada Lisp
.AND. and && and and
.OR. or || or or
.NOT. not ! not
xor
not
xor
22
Odd Boolean Expressions in C
• C (until very recently) had no Boolean type
– used int 0 for false, and 1 or nonzero for true
• One odd characteristic of C’s expressions:
x < y < z
– Is a legal expression, but
– the result is not what you might expect! - I.e.(x<y)&(y<z)
– What does it do?
• Hint: C is left associative, what is z compared to?
23
Operators Precedence
• Precedence of Ada operators:
**, abs, not
*, /, mod, rem
[unary] -, +
[binary] +, -, &
[relative] in, not in
and, or, xor, then, or, else
• C, C++, and Java have
– over 40 operators, and
– at least 15 different levels of precedence
24
Short Circuit Evaluation
• Suppose Java did not use short-circuit evaluation
• Problem
– table look-up
for (i = 1; i < a.length) && (a [i] != x); i++) {}
• Problem: reading from a file until eof
• Short-circuit evaluation has the problem of side effects
e.g. (a > b) || (b++ / 3) vs. a > b) || (++b / 3)
25
Short Circuit Evaluation in PLs
• C, C++, Java
– Provide short-circuit Boolean operators && and||
– As well as operators that are not short circuit: & and|
– why both?
• Ada
– More operators, programmer can specify either
– Not short circuit using and, or
– Short-circuit using and then, or else
• FORTRAN 77
– short circuit, any side-affected variables must be set to
undefined
26
Assignment Statements
• Assignment operator syntax
– = FORTRAN, BASIC, PL/I, C, C++, Java
– := ALGOLs, Pascal, Ada
– setf/setq in Lisp
• Very bad if assignment = overloaded as relational =
– e.g. in PL/I: A = B = C;
• Note difference from C’s
– ==
– A common C error using = when it should be ==
27
Complex Assignment Statements
• Multiple targets (PL/I)
A, B = 10
• Compound assignment operators in C, C++, Java
sum += next;
• Conditional targets in C, C++, Java
(first == true) ? total : subtotal = 0
• Unary assignment operators in C, C++, Java
a++;
• C, C++, and Java treat = as an arithmetic binary
operator
a = b * (c = d * 2 + 1) + 1
28
Assignment Statement as an Expression
• In C, C++, Java
– Assignment statements produce results
– So, they can be used as operands in expressions
while ((ch = getchar()) != EOF){…}
• Disadvantages
– Another kind of expression side effect
– Readability
29
Mixed-Mode Assignment
• FORTRAN, C, C++
– any numeric value can be assigned to any numeric variable
– conversion is automatic
• Pascal
– integers can be assigned to reals, but
– reals cannot be assigned to integers
• must specify truncate or round
• Java
– only widening assignment coercions are done
• Ada
– no assignment coercion
• Lecture-specific question:
– Advantages/disadvantages of these approaches?

Contenu connexe

Tendances

CBSE Class XI :- Operators in C++
CBSE Class XI :- Operators in C++CBSE Class XI :- Operators in C++
CBSE Class XI :- Operators in C++Pranav Ghildiyal
 
Variables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detailVariables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detailgourav kottawar
 
Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressionsvishaljot_kaur
 
Operation and expression in c++
Operation and expression in c++Operation and expression in c++
Operation and expression in c++Online
 
Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programmingsavitamhaske
 
Types of operators in C
Types of operators in CTypes of operators in C
Types of operators in CPrabhu Govind
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
Operator in c programming
Operator in c programmingOperator in c programming
Operator in c programmingManoj Tyagi
 
Basic c operators
Basic c operatorsBasic c operators
Basic c operatorsdishti7
 
Operators in Python
Operators in PythonOperators in Python
Operators in PythonAnusuya123
 
Operators
OperatorsOperators
OperatorsKamran
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in JavaAbhilash Nair
 

Tendances (20)

Operator.ppt
Operator.pptOperator.ppt
Operator.ppt
 
Operators in C & C++ Language
Operators in C & C++ LanguageOperators in C & C++ Language
Operators in C & C++ Language
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
CBSE Class XI :- Operators in C++
CBSE Class XI :- Operators in C++CBSE Class XI :- Operators in C++
CBSE Class XI :- Operators in C++
 
Variables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detailVariables, Data Types, Operator & Expression in c in detail
Variables, Data Types, Operator & Expression in c in detail
 
Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressions
 
Operation and expression in c++
Operation and expression in c++Operation and expression in c++
Operation and expression in c++
 
Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programming
 
Operators in python
Operators in pythonOperators in python
Operators in python
 
Types of operators in C
Types of operators in CTypes of operators in C
Types of operators in C
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
COM1407: C Operators
COM1407: C OperatorsCOM1407: C Operators
COM1407: C Operators
 
Operators
OperatorsOperators
Operators
 
Operator in c programming
Operator in c programmingOperator in c programming
Operator in c programming
 
Basic c operators
Basic c operatorsBasic c operators
Basic c operators
 
Java 2
Java 2Java 2
Java 2
 
Python : basic operators
Python : basic operatorsPython : basic operators
Python : basic operators
 
Operators in Python
Operators in PythonOperators in Python
Operators in Python
 
Operators
OperatorsOperators
Operators
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
 

En vedette

En vedette (16)

General principles of poultry medication
General principles of poultry medicationGeneral principles of poultry medication
General principles of poultry medication
 
Selección de libros para promover la lectura
Selección de libros para promover la lecturaSelección de libros para promover la lectura
Selección de libros para promover la lectura
 
Palmcoien classification
Palmcoien classificationPalmcoien classification
Palmcoien classification
 
Mind the mind by Chaitanya Charan Das
Mind the mind by Chaitanya Charan DasMind the mind by Chaitanya Charan Das
Mind the mind by Chaitanya Charan Das
 
Evaluación desempeño docente 2017 30022017 cgie
Evaluación desempeño docente 2017 30022017 cgieEvaluación desempeño docente 2017 30022017 cgie
Evaluación desempeño docente 2017 30022017 cgie
 
Design Process of Agriculture Ontologies
Design Process of Agriculture OntologiesDesign Process of Agriculture Ontologies
Design Process of Agriculture Ontologies
 
Turnitin student mar60
Turnitin student mar60Turnitin student mar60
Turnitin student mar60
 
C++ Tutorial
C++ TutorialC++ Tutorial
C++ Tutorial
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01Lecture 10 semantic analysis 01
Lecture 10 semantic analysis 01
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Type conversion
Type conversionType conversion
Type conversion
 
Intermediate code generation1
Intermediate code generation1Intermediate code generation1
Intermediate code generation1
 
[Webinar] New from Google: Algorithm changes & social media analytics
[Webinar] New from Google: Algorithm changes & social media analytics[Webinar] New from Google: Algorithm changes & social media analytics
[Webinar] New from Google: Algorithm changes & social media analytics
 
Que es soft layer / IBM
Que es soft layer / IBMQue es soft layer / IBM
Que es soft layer / IBM
 
Examen muestra 2
Examen muestra 2Examen muestra 2
Examen muestra 2
 

Similaire à Expressions in c++

7 expressions and assignment statements
7 expressions and assignment statements7 expressions and assignment statements
7 expressions and assignment statementsMunawar Ahmed
 
7 expressions and assignment statements
7 expressions and assignment statements7 expressions and assignment statements
7 expressions and assignment statementsjigeno
 
07 control+structures
07 control+structures07 control+structures
07 control+structuresbaran19901990
 
Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Jamshid Hashimi
 
L3 operators
L3 operatorsL3 operators
L3 operatorsteach4uin
 
L3 operators
L3 operatorsL3 operators
L3 operatorsteach4uin
 
L3 operators
L3 operatorsL3 operators
L3 operatorsteach4uin
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 
Python-Certification-Training-Day-1-2.pptx
Python-Certification-Training-Day-1-2.pptxPython-Certification-Training-Day-1-2.pptx
Python-Certification-Training-Day-1-2.pptxmuzammildev46gmailco
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variablesTony Apreku
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Rasan Samarasinghe
 
Java class 1
Java class 1Java class 1
Java class 1Edureka!
 
Functional Programming in JavaScript & ESNext
Functional Programming in JavaScript & ESNextFunctional Programming in JavaScript & ESNext
Functional Programming in JavaScript & ESNextUnfold UI
 

Similaire à Expressions in c++ (20)

7 expressions and assignment statements
7 expressions and assignment statements7 expressions and assignment statements
7 expressions and assignment statements
 
Ch4 Expressions
Ch4 ExpressionsCh4 Expressions
Ch4 Expressions
 
Chapter 07
Chapter 07 Chapter 07
Chapter 07
 
Chap 3(operator expression)
Chap 3(operator expression)Chap 3(operator expression)
Chap 3(operator expression)
 
Ppl
PplPpl
Ppl
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
 
7 expressions and assignment statements
7 expressions and assignment statements7 expressions and assignment statements
7 expressions and assignment statements
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
 
Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1
 
L3 operators
L3 operatorsL3 operators
L3 operators
 
L3 operators
L3 operatorsL3 operators
L3 operators
 
L3 operators
L3 operatorsL3 operators
L3 operators
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Python-Certification-Training-Day-1-2.pptx
Python-Certification-Training-Day-1-2.pptxPython-Certification-Training-Day-1-2.pptx
Python-Certification-Training-Day-1-2.pptx
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Java class 1
Java class 1Java class 1
Java class 1
 
8 statement level
8 statement level8 statement level
8 statement level
 
Functional Programming in JavaScript & ESNext
Functional Programming in JavaScript & ESNextFunctional Programming in JavaScript & ESNext
Functional Programming in JavaScript & ESNext
 

Dernier

Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxDr. Asif Anas
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxDr. Santhosh Kumar. N
 
5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...CaraSkikne1
 
Philosophy of Education and Educational Philosophy
Philosophy of Education  and Educational PhilosophyPhilosophy of Education  and Educational Philosophy
Philosophy of Education and Educational PhilosophyShuvankar Madhu
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxheathfieldcps1
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17Celine George
 
The Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsThe Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsEugene Lysak
 
How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17Celine George
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphNetziValdelomar1
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17Celine George
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxEduSkills OECD
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationMJDuyan
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfMohonDas
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...Nguyen Thanh Tu Collection
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptxraviapr7
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxKatherine Villaluna
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfYu Kanazawa / Osaka University
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfMohonDas
 

Dernier (20)

Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptx
 
M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptx
 
5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...
 
Philosophy of Education and Educational Philosophy
Philosophy of Education  and Educational PhilosophyPhilosophy of Education  and Educational Philosophy
Philosophy of Education and Educational Philosophy
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17
 
Prelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quizPrelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quiz
 
The Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsThe Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George Wells
 
How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a Paragraph
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
 
Benefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive EducationBenefits & Challenges of Inclusive Education
Benefits & Challenges of Inclusive Education
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdf
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptx
 
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdf
 

Expressions in c++

  • 1. 1 Expressions, Evaluation and Assignments • Arithmetic expressions • Overloaded operators • Type conversions • Relational and Boolean expressions • Short-circuit evaluation • Assignment statements • Mixed-mode assignment statements • Sebesta Chapter 7
  • 2. 2 Expressions • Expressions are fundamental means of specifying computations in programming languages • Understanding how expressions are evaluated requires knowing the order in which operator and operand are evaluated • Essence of imperative languages is the dominant role of assignment statements, including expressions
  • 3. 3 Arithmetic Expressions • Evaluation of numeric expressions – Motivation for the development of PLs • Remember trajectory tables? • Arithmetic expressions consist of – Operators – Operands – Parentheses/delimiters – Function calls
  • 4. 4 Design Issues for Arithmetic Expressions 1. What are the operator precedence rules? 2. What are the operator associativity rules? 3. What is the order of operand evaluation? 4. Are there restrictions on operand evaluation side effects? 5. Is user-defined operator overloading supported? 6. What mode mixing in expressions is allowed?
  • 5. 5 Arity of Arithmetic Expressions • Arity – Number of operands/arguments of a function • A unary operator has one operand • A binary operator has two operands – Most common operators • A ternary operator has three operands • Some languages support N-ary operators – In Lisp, a benefit of prefix representation (* pi r r) vs. pi*r*r or pi*r^2
  • 6. 6 Operator Precedence Rules • Precedence define the order in which adjacent operators are evaluated – Adjacent - separated by at most one operand • Different PLs have different precedence levels • Typical precedence levels – highest to lowest 1. Parentheses 2. Unary operators 3.** (exponentiation, if the language supports it) 4.*, /, % (modulo) 5.+, -
  • 7. 7 Operator Associativity Rules • Define the order in which adjacent operators with the same precedence level are evaluated • Typical associativity rules – Left to right, except ** which is right to left – Unary operators may associate right to left (e.g., FORTRAN) • APL is different – All operators have equal precedence and – All operators associate right to left! • Parentheses override precedence and associativity rule
  • 8. 8 Expression Evaluation Process • Order of evaluation is crucial 1. Variables – fetch value from memory 1. Constants – either implicit in instruction – or fetch from memory 1. Parenthesized expressions – evaluate all operands and operators first 1. Function references – the most interesting
  • 9. 9 Functions/Procedures Result/ Return value Input/Output Side Effects Function/Procedure Arguments/ Parameters • Parameters – pass by value (in) or by reference (in/out) • Return value • Input/Output • Side Effects
  • 10. 10 Side Effects • Side effect – a function or procedure changes a two-way parameter or a non-local variable • A major problem with side effects: – When a function referenced in an expression alters another operand of the expression; e.g., for a parameter change: a = 10; b = a + fun(&a); /*Assume fun changes its parameter*/ • Results of the expression depend on the order of evaluation of statements!! – why is this bad?
  • 11. 11 Solution 1: Prohibit Side Effects! 1. Language definition prohibits side effects – No two-way parameters – No non-local references • Advantage – It works! – E.g. functional languages • Disadvantages: – Need flexibility of two-way parameters and non-local variables • What about C? What about Java? – Copying of parameters to avoid side effects
  • 12. 12 Solution 2: Fix Evaluation Order 2. Operand evaluation order is fixed in language definition • Advantage – We always know how expression will be evaluated • Disadvantage – This limits some compiler optimizations
  • 13. 13 Conditional Expressions • Ternary operator <cond> ? <expr1> : <expr2> – Same as if (<cond> ) <expr1> else <expr2> – C, C++, and Java <condition> average (count == 0) ? 0 : sum / count – Lisp: (if <test> <do-if-true> <do-ifnot>) • Short-circuit evaluation means 1. Evaluate test first and then 2. Evaluate only the branch taken • e.g. avoid division by zero above
  • 14. 14 Overloading Operators • Operator overloading – use of an operator for more than one purpose • Some are common (e.g., + for int and float) • Some are potential trouble • e.g., * in C and C++, / for int and float in Java – Loss of compiler error detection • Missing operand should be a detectable error – Some loss of readability – Can be avoided by introduction of new symbols e.g., Pascal’s div
  • 15. 15 User-defined Overloaded Operators • C++ and Ada allow user-defined overloaded operators • Problems – Users can define nonsense operations – Readability may suffer, even when the operators make sense
  • 16. 16 Type Conversions • Narrowing conversion – converts to a “smaller” type (type has fewer values) • e.g., float to int • 3.99 to 4 • Widening conversion – converts to a type that includes all values of the original type – or at least an approximation of each • e.g., int to float • 4 to 4.0f
  • 17. 17 Type Conversions • Mixed-mode expression – Operands of different types • Coercion – An implicit type conversion • Disadvantage – Decreases the type error detection ability of the compiler • In most languages, widening conversions of numeric types in expressions can be coerced • In Ada, there are virtually no coercions in expressions
  • 18. 18 Explicit Type Conversions • In C, C++, Ada, Java called casts • E.g., Ada: FLOAT (INDEX) --INDEX is INTEGER type – converts to floating point • E.g., Java: float speed = 45.5; (int) speed; /* =45; cuts off fractional part*/
  • 19. 19 Errors in Expressions 1. Inherent properties of mathematical functions – e.g. division by zero, infinity 1. Approximate representations – Fractions (e.g. 2/3, 0.1) and irrational numbers like π and e – Approximate huge integers with floating point 1. Limitations of computer arithmetic – e.g. overflow, underflow • If ignored by the run-time system (may even be undetectable) can lead to crashes, erroneous output, unpredictable behavior • Less of a problem in some languages! – E.g. exact fractions and huge integers in Lisp prevent errors of type 2 & 3
  • 20. 20 Relational Operators, Boolean Expressions • Boolean data type – 2 values • True • False • Boolean expression – Has relational operators and operands of various types – Evaluates to a Boolean value – Operator symbols vary among languages • e.g.not equal – != – /= – .NE. – <> – #
  • 21. 21 Boolean Expressions • Operands are Boolean • Result is Boolean Boolean operator comparison F77 FORTRAN 90 C Ada Lisp .AND. and && and and .OR. or || or or .NOT. not ! not xor not xor
  • 22. 22 Odd Boolean Expressions in C • C (until very recently) had no Boolean type – used int 0 for false, and 1 or nonzero for true • One odd characteristic of C’s expressions: x < y < z – Is a legal expression, but – the result is not what you might expect! - I.e.(x<y)&(y<z) – What does it do? • Hint: C is left associative, what is z compared to?
  • 23. 23 Operators Precedence • Precedence of Ada operators: **, abs, not *, /, mod, rem [unary] -, + [binary] +, -, & [relative] in, not in and, or, xor, then, or, else • C, C++, and Java have – over 40 operators, and – at least 15 different levels of precedence
  • 24. 24 Short Circuit Evaluation • Suppose Java did not use short-circuit evaluation • Problem – table look-up for (i = 1; i < a.length) && (a [i] != x); i++) {} • Problem: reading from a file until eof • Short-circuit evaluation has the problem of side effects e.g. (a > b) || (b++ / 3) vs. a > b) || (++b / 3)
  • 25. 25 Short Circuit Evaluation in PLs • C, C++, Java – Provide short-circuit Boolean operators && and|| – As well as operators that are not short circuit: & and| – why both? • Ada – More operators, programmer can specify either – Not short circuit using and, or – Short-circuit using and then, or else • FORTRAN 77 – short circuit, any side-affected variables must be set to undefined
  • 26. 26 Assignment Statements • Assignment operator syntax – = FORTRAN, BASIC, PL/I, C, C++, Java – := ALGOLs, Pascal, Ada – setf/setq in Lisp • Very bad if assignment = overloaded as relational = – e.g. in PL/I: A = B = C; • Note difference from C’s – == – A common C error using = when it should be ==
  • 27. 27 Complex Assignment Statements • Multiple targets (PL/I) A, B = 10 • Compound assignment operators in C, C++, Java sum += next; • Conditional targets in C, C++, Java (first == true) ? total : subtotal = 0 • Unary assignment operators in C, C++, Java a++; • C, C++, and Java treat = as an arithmetic binary operator a = b * (c = d * 2 + 1) + 1
  • 28. 28 Assignment Statement as an Expression • In C, C++, Java – Assignment statements produce results – So, they can be used as operands in expressions while ((ch = getchar()) != EOF){…} • Disadvantages – Another kind of expression side effect – Readability
  • 29. 29 Mixed-Mode Assignment • FORTRAN, C, C++ – any numeric value can be assigned to any numeric variable – conversion is automatic • Pascal – integers can be assigned to reals, but – reals cannot be assigned to integers • must specify truncate or round • Java – only widening assignment coercions are done • Ada – no assignment coercion • Lecture-specific question: – Advantages/disadvantages of these approaches?