SlideShare ist ein Scribd-Unternehmen logo
1 von 61
Chapter 07 Arithmetic Expression , Overloaded Operators , Type Conversions , Relational and Boolean Expressions, Short Circuit Evaluation , Assignment Statements , Mixed Mode Assignments BY Abdul-Wahab
Issues of Imperative languages. Character , string matching expressions in CH 6.
Fundamental means of specifying computation. Syntax , BNF Form. Semantics , What do they mean? And evaluated.
Expression Evaluation Order of Operators and Operator Evaluation. Associatively and Precedence rules of PL Operand Evaluation is unstated and left on Implementers. Different Implementation results in different results. Other issues in Semantics are Type Mismatches , Coercion and Short Circuit Evaluation.
Assignment statements have dominant role in Imperative Languages. Purpose of Assignment Statement is to change the state of the variable. Non Imperative Languages e.g Functional Programming Languages use variable as parameters of Functions. Simple Assignment Statement Target   := Expression
Arithmetic Expressions It all started with automatic Evaluation of arithmetic Expressions from First High level Languages. Most Conventions were taken from Mathematics. In PL , Operands , Operators , Parenthesis and function call are part of  Arithmetic Expression.
Design issues of arithmetic expression What are the operator precedence rules. What are operator Associativity rules. What is the order of Operand Evaluation. Are there restrictions on Operand Evaluation Side effect. Does the Language Allow User-defined  operator Overloading. What type mixing is allowed in expression.
Operator Evaluation Order Precedence Value on expression may depends on it. a + b * c Operator precedence rules from Mathematicians. Rules almost same for all Imperative languages. U.S =>   PEMDAS  "Please Excuse My Dear Aunt Sally".  It stands for "Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction".
Why Precedence of Operators Logic by Mathematicians Multiply is based on Addition
Unary version of Addition and Subtraction. Unary Addition is called Identity Operator. Input = output , no effect on Operand. Ellis and Storstroup named it as Historical mistake and useless operator. Java and C # has a effect , it coercively change short ,byte to int. C changes it to int type. A  +  ( - B )   * C        is legal  but A  +    - B   * C         usually is not  (legal in C based language)
Precedence of Unary Operator -A / B -A * B -A ** B in Ruby ADA, FORTRAN and BASIC (   **   has high precedence) -A  **  B  Is Equivalent to  - ( A **  B  )
Unary and MOD In Ada , Mod has higher precedence than Unary. - 17 mod 5 Is equivalent to  (17 mod 5)
What is the difference between  Mod and Rem ?
APL , has single level precedence for all operators .
Associativity a – b + c – d a + b - c When an expression contains two adjacent occurrences of operators with the same level of precedence , the question of which operator is evaluated first is answered by Associativity. Adjacent operators are separated by a single operand with same level of precedence.
Exponent Operator Usually from  Left to Right Exponentiation is from Right to left (Ruby and FORTRAN) A ** B ** C In Ada   ** is non Assosiative A ** B ** C  is illegal Use of Parenthesis to do the job In Ada   ** is non Assosiative In Visual Basic  ^ is for exponentiation and is right associative.
Associative rules for imperative languages
Single Level Precedence of   APL Total Dependency on Associativity Right to Left  A  X   B  + C
Associativity of Operators Addition , Multiplication mathematically Associative Subtraction and division is not A+B+C  		order doesn’t matter In Computers  This doesn’t hold for  floating point arithmetic A+ A –A -A A+A –B –B Suppose  A and B are very large numbers Overflow problems and optimization  ( C , C++ , ??)
Paranthesis Used to alter the precedence and Associativity. Advantage Readability and  More control , No need to remember Not good for simple expression Demerit of not using Parenthesis Over complexities
Ruby Expressions Pure Object Oriented Programming Every data value , including literal is an object. Ruby supports collection of Arithmetic and Logical operation so C Based Language. But Every thing is implemented as method e.ga+b Overloading of predefined methods (Not recommended) But Useful in some cases Operator overloading for user defined types
Conditional Expressions Ternary Operator    ?: If – then – else statement If (count == 0 ) Average = 0; Else Average = sum / count; Expression_1   ?    Expression_2    :    expression_3 			Expression_1  is Boolean expression Average =   (count ==0 ) ?   0    :     sum/count
Operand Evaluation Order Expression    OPERATOR   Expression Variables in expression are evaluated by fetching their values from memory (Constant case may be different) If Expression is paranthesized then all its variables must be evaluated before it can be used as an operand If there is no side effect  then  the Operand Order is irrelevant Lets look at the  Operand Evaluation which has side effects
Side Effect A side effect of a function called a functional side effect. A Function changing the global variable By use of Reference variable , Pass by Reference  a + fun (a) a + fun(b) Void fun(){ // assuming a is a global variable a }
Note : There are not functional side effects in Mathematics There are probably no side effects in pure functional Programming languages Because there context is irrelevant to its meaning
Two Possible Solutions to the Problem:  1. Write the language definition to disallow functional side effects  No two-way parameters in functions  No non-local references in functions  Advantage: it works!  Disadvantage: Programmers want the flexibility of two-way parameters (what about C?) and non-local references  2. Write the language definition to demand that operand evaluation order be fixed  Disadvantage: limits some compiler optimizations
Java provides left to right operand evaluation. Ada  let you specify the order
Overloaded Operators Arithmetic Operators are often used for more than one purpose. + , for integer and float addition , catenation This multiple use of operators is called Operator Overloading Operator Overloading ( Function Overloading )
It is acceptable , if readability and reliability is not compromised. & ,  Address , Bitwise AND , reference Operator. Deterimental to readability and reliabilty E.g    x =  z  & y             =>           x = &y Missing the z will go undetected by compiler.
Unary Minus operator (Less Serious) X =  z – y         =>        X  =   -  y Distinct Operation not only increase readability but are sometimes convenient to use for common operation as well E.g division operator
Sum , count (int)     ,   avg (float) avg =   sum  /    count Integer division Soln: Separate Operator , ( / , div )   Pascal Inferencing on LHS ,  both operand will  coercively converted to float Dynamic Language like php based on the result generate the type Java Script provides only float division.
FORTRAN , Ada , C++ , C # , allows the programmer to further overload operator symbol. e.g     between scalar and integer array. could overload *  whenever  For       int   *   int array And for Abstract User defined type . E.g Student.
Evaluation When Sensibly used could improve Readability For Matrix Operations A * B + C * D MatrixAdd( MatrixMult(A,B)  , MatrixMult(C,D)  ) Demerits of Operator Overloading for UDTs Student1 < Student 2
Non Overloadable Operators E.g    dot  .    ,   ::    etc Not Taken by Java Taken by C Sharp
Type Conversions Narrowing Conversion Convert a value that cannot store all the approximation of original type Double to float  ( much higher in java) Widening Conversion Consider as safe but not always Byte to integer Float to double  Int to long  Exception  ( they may result in lost of accuracy) Int    to float  may loose accuracy upto 2 decimal points
Coercion in Expression Mix Mode Expression String +  int Int is coerced to be a string Coercion is good or bad Programmer vs compiler Mix Mode expressions are legal in Java  int a; float   b , c , d; ….. d = b * a;	// simply   coerced   a   to float
Ada , does not allow much Mix Mode Expression Exception is with  the  ( ** )Exponential operator. First operand    integer/ float Second Operand    integer Other exceptions of Mix Mode Expressions in Ada are with subtypes.
Byte , short in C based language When used with operator are coerced with int type.   A = b + c Utilization of Memory is efficient Handy in large arrays
Explicit Type Conversion Both Narrowing and Widening In C based languages it is called Cast. When Narrowing conversion result in significant lose , a warning or error is produced. ( int ) angle Why use brackets  (long  int ) Ada  ,    Float (sum)
Errors in Expression Statically and dynamicaly type checking avoid these problems Limitations of computer arithmetic , mathematical arithmetic. Aritmetic overflow , underflow , divide by zero. Mathemitally disallowed doesn’t mean programmer will not attempt it. Solution: Exception handling in Chapter 14
Relational and Boolean Expressions Relational Expression Comparison Operator Value of Relational Operator is Boolean if provided. Simple for arithmetic VS  complex for strings 2 < 3  		VS      abdulvsahad Fortran 95 	NE	<> Ada 		/= SQL  		<> C-Based	!=
Java script and PHP has two additional operators ===     and    !== == is coercive   while    === is not “77” == 77   is true    VS    “77” === 77  is false Ruby == for coercive and  eql ? For non coercive Relationa Operators always have low Precedence. A+1 < b * 2
Boolean Expression AND    OR   NOT   Exclusive OR Mathematicaly   AND    and  OR are of same precedence  so in  Ada But not in C ,  AND has higher precedence ARW ->  RE  ->   BE
C has no Boolean type A > b > c Left assosiative A> b is evaluated first  and 0 or 1 is returned There is never a comparison of b and c 2<7<1 2<7>1
Ruby , Perl { AND , OR  , && , || } And  , OR    have same precedence Spelled version have lower precedence && has higher precedence than ||
Arithmetic and Non Arithmetic Operators of C Based Language  and at least 14 different level of precedence. Richness of collection of oeprators and complexities of Expressions C , C++ Readability prefer  boolean over numeric Coz , numeric is a legal operand to Boolean Operator
Short Circuit Evaluation Non Strict Evaluation A Short circuit Evaluation of an expression is one in which the result is determined without evaluating all of the operands and/ or operators E.g		(13 * a )   * ( b + c +d * e / 3 ) + (e**d) If      a= 0 , then no need to evaluate others ( b + c +d * e / 3 ) + (e**d)   * *  ( a – b ) If    a-b == 0 then result is 1 However This is quite difficult to detect at run time so never taken.
Boolean Expression ( a >= 0 ) && (b < 10) Second Expression is independent False   AND   ?  Equals    false
OR Side effect may occur on complete evaluation Program correctness depends on it. ( a > b) || ( (b++) / 3 ) 	Order is sometimes not mentioned left or right
Ada provides    and then       or else to specify Shortcircuit Evaluation 	Index :=1 	while ( Index < count   )  and then ( array[index]  /= key) Loop: 	Index := index + 1; End loop
In C Based Language  &&  and & || and | What are the issues with it ?
Assignment One of the central constructs in Imperative languages. Imperative languages are based on von neuman architecture. syntax <target_variable>   <assignment_operator>  <expression>  Most  PL use of    =    as  a assignment operator ALGOL 60  introduced   :=  and then Ada followed C   may have embedded assignment statements in expression. Fortran and Ada , Assignment can appear as Standalone statement Single target variable
Conditional Targets Flag 	?	 count1 	: 	count2 	= 0; Equivalent to  if ( Flag ) 		Count1 = 0; else 		Count 2 = 0;
Compound Assignment Operators  a  = a+b; a += b; Introduced by ALGOL 68 Now in all Imperative languages
Unary Assignment Operators Count   =   count   +  1  Count ++; Preceede / follow the operand Sum = ++ count; Count  = count + 1 Sum = count Sum = count++; Sum = count Count  = count + 1 -count ++	( when two unary operators to same operand , Association is right to left ) (count ++)	//  like this Rather than  ( - count )++	//  not like this
Assignment as Expression In C Based Languages , Perl , Javascript Assignment statement generates a result Like a binary operator (but it effects its second operand) if( a= 2){	//  true in C , C++           if ( 2 ){ } else{ } Languages which does support  , Assignment Operator has less precedence than relational operators If (         ( a=b  )     !=  c  ) Without  paranthesis    it would be             If (         ( a=  (b !=  c ) )          // b != c  produce 0 or 1
Contn’d Side effect  of Assignment in Expression Readability Reliability Multiple Assignment Sum = count = 0;
List Assignment Perl and ruby provide it ($first , $second , $ third) = (20,40,60); ($first , $second) = ($second , $first) In C Based anguages Int ar[20] = {1,2,3,4,5,6} What If # of variables on R.H.S and L.H.S are mismatched Less and greater cases on R.H.S Ruby has more Elaborate cases
Mix Mode Assignment In case of type mismatch , use coercion or not. Fortran , C , C++ and Perl use coercion for mixed mode assignment. Java and C #  use coercion for widening conversion is ok and also in some narrowing cases as well  e.g  int to char if it is in range. Int can be float but not vice verca In All language coerced after RHS expression evaluation One alternative is to coerced all operands to type of LHS Ruby and Python types are associated with objects , so there are no mix mode assignment.
Summary Expressions consist of constants , variables , parenthesis , function calls and operators. Assignment statements include target variable , assignment operators and expressions. Semantics of an Expression is determined in large by the order of the evaluation of operators. The Associativity and precedence rules for operators in the expression of a language determine the order of Operator evaluation in those expresion Operand evaluation  order is important in functional side effects are possible. Type Conversion can be widening or narrowing . Some narrowing conversion can produced erroneous results. Implicit Conversion or coercion  in expressions are common, although they eliminate the error detection benefit of type checking , thus lowering reliability. Assignment statements have appeared in a wide variety of forms , including conditional targets , assigning operators and list assignments.
Practices Solve the Problem set given at the end of this chapter. Practice each topic in your Assigned language and favorite language. E.g 	Ruby , java etc References : Most material other than the text book is taken from Wikipedia.

Weitere ähnliche Inhalte

Was ist angesagt?

Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaEdureka!
 
Binary expression tree
Binary expression treeBinary expression tree
Binary expression treeShab Bi
 
CMSC 56 | Lecture 15: Closures of Relations
CMSC 56 | Lecture 15: Closures of RelationsCMSC 56 | Lecture 15: Closures of Relations
CMSC 56 | Lecture 15: Closures of Relationsallyn joy calcaben
 
Input and Output In C Language
Input and Output In C LanguageInput and Output In C Language
Input and Output In C LanguageAdnan Khan
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions Ganesh Samarthyam
 
Ethical and Social Issues in ICT
Ethical and Social Issues in ICTEthical and Social Issues in ICT
Ethical and Social Issues in ICTRoshanMaharjan13
 
Lecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data StructuresLecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data StructuresHaitham El-Ghareeb
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators pptViraj Shah
 
Conversion from infix to prefix using stack
Conversion from infix to prefix using stackConversion from infix to prefix using stack
Conversion from infix to prefix using stackHaqnawaz Ch
 
Hashing in datastructure
Hashing in datastructureHashing in datastructure
Hashing in datastructurerajshreemuthiah
 
Operators in python
Operators in pythonOperators in python
Operators in pythoneShikshak
 
Independent and Dependent Events
Independent and Dependent EventsIndependent and Dependent Events
Independent and Dependent Eventsctybishop
 
Unit I - Evaluation of expression
Unit I - Evaluation of expressionUnit I - Evaluation of expression
Unit I - Evaluation of expressionDrkhanchanaR
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
C multiple choice questions and answers pdf
C multiple choice questions and answers pdfC multiple choice questions and answers pdf
C multiple choice questions and answers pdfchoconyeuquy
 
Hacking And Its Prevention
Hacking And Its PreventionHacking And Its Prevention
Hacking And Its PreventionDinesh O Bareja
 
Searching in Arrays
Searching in ArraysSearching in Arrays
Searching in ArraysDhiviya Rose
 
10. switch case
10. switch case10. switch case
10. switch caseWay2itech
 

Was ist angesagt? (20)

Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
 
Binary expression tree
Binary expression treeBinary expression tree
Binary expression tree
 
CMSC 56 | Lecture 15: Closures of Relations
CMSC 56 | Lecture 15: Closures of RelationsCMSC 56 | Lecture 15: Closures of Relations
CMSC 56 | Lecture 15: Closures of Relations
 
Input and Output In C Language
Input and Output In C LanguageInput and Output In C Language
Input and Output In C Language
 
number theory Rosen
number theory Rosen   number theory Rosen
number theory Rosen
 
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
OCP Java SE 8 Exam - Sample Questions - Lambda Expressions
 
Ethical and Social Issues in ICT
Ethical and Social Issues in ICTEthical and Social Issues in ICT
Ethical and Social Issues in ICT
 
Lecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data StructuresLecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data Structures
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators ppt
 
Conversion from infix to prefix using stack
Conversion from infix to prefix using stackConversion from infix to prefix using stack
Conversion from infix to prefix using stack
 
Hashing in datastructure
Hashing in datastructureHashing in datastructure
Hashing in datastructure
 
Operators in python
Operators in pythonOperators in python
Operators in python
 
Independent and Dependent Events
Independent and Dependent EventsIndependent and Dependent Events
Independent and Dependent Events
 
Unit I - Evaluation of expression
Unit I - Evaluation of expressionUnit I - Evaluation of expression
Unit I - Evaluation of expression
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
C multiple choice questions and answers pdf
C multiple choice questions and answers pdfC multiple choice questions and answers pdf
C multiple choice questions and answers pdf
 
Hacking And Its Prevention
Hacking And Its PreventionHacking And Its Prevention
Hacking And Its Prevention
 
Searching in Arrays
Searching in ArraysSearching in Arrays
Searching in Arrays
 
Prefix Postfix
Prefix PostfixPrefix Postfix
Prefix Postfix
 
10. switch case
10. switch case10. switch case
10. switch case
 

Ähnlich wie Chapter 07

7 expressions and assignment statements
7 expressions and assignment statements7 expressions and assignment statements
7 expressions and assignment statementsjigeno
 
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
 
programing in c PPT Gaurav Nautiyal.pptx
programing in c PPT Gaurav Nautiyal.pptxprograming in c PPT Gaurav Nautiyal.pptx
programing in c PPT Gaurav Nautiyal.pptxHacker301428
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statementsİbrahim Kürce
 
C Prog. - Operators and Expressions
C Prog. - Operators and ExpressionsC Prog. - Operators and Expressions
C Prog. - Operators and Expressionsvinay arora
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001Ralph Weber
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++bajiajugal
 
C operators
C operatorsC operators
C operatorsGPERI
 
Verilog operators.pptx
Verilog  operators.pptxVerilog  operators.pptx
Verilog operators.pptxVandanaPagar1
 
Computer programming in C. Library functions in C.
Computer programming in C. Library functions in C.Computer programming in C. Library functions in C.
Computer programming in C. Library functions in C.LamiyQurbanlKomptert
 
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
 
M.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageM.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageDr.Florence Dayana
 

Ähnlich wie Chapter 07 (20)

7 expressions and assignment statements
7 expressions and assignment statements7 expressions and assignment statements
7 expressions and assignment statements
 
C basics
C basicsC basics
C basics
 
C basics
C basicsC basics
C basics
 
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
 
Basic Of C language
Basic Of C languageBasic Of C language
Basic Of C language
 
Ch4 Expressions
Ch4 ExpressionsCh4 Expressions
Ch4 Expressions
 
Ppl
PplPpl
Ppl
 
programing in c PPT Gaurav Nautiyal.pptx
programing in c PPT Gaurav Nautiyal.pptxprograming in c PPT Gaurav Nautiyal.pptx
programing in c PPT Gaurav Nautiyal.pptx
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
 
C Prog. - Operators and Expressions
C Prog. - Operators and ExpressionsC Prog. - Operators and Expressions
C Prog. - Operators and Expressions
 
C program
C programC program
C program
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
C operators
C operatorsC operators
C operators
 
05 operators
05   operators05   operators
05 operators
 
Verilog operators.pptx
Verilog  operators.pptxVerilog  operators.pptx
Verilog operators.pptx
 
Computer programming in C. Library functions in C.
Computer programming in C. Library functions in C.Computer programming in C. Library functions in C.
Computer programming in C. Library functions in C.
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
M.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageM.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C Language
 

Kürzlich hochgeladen

Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 

Kürzlich hochgeladen (20)

Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 

Chapter 07

  • 1. Chapter 07 Arithmetic Expression , Overloaded Operators , Type Conversions , Relational and Boolean Expressions, Short Circuit Evaluation , Assignment Statements , Mixed Mode Assignments BY Abdul-Wahab
  • 2. Issues of Imperative languages. Character , string matching expressions in CH 6.
  • 3. Fundamental means of specifying computation. Syntax , BNF Form. Semantics , What do they mean? And evaluated.
  • 4. Expression Evaluation Order of Operators and Operator Evaluation. Associatively and Precedence rules of PL Operand Evaluation is unstated and left on Implementers. Different Implementation results in different results. Other issues in Semantics are Type Mismatches , Coercion and Short Circuit Evaluation.
  • 5. Assignment statements have dominant role in Imperative Languages. Purpose of Assignment Statement is to change the state of the variable. Non Imperative Languages e.g Functional Programming Languages use variable as parameters of Functions. Simple Assignment Statement Target := Expression
  • 6. Arithmetic Expressions It all started with automatic Evaluation of arithmetic Expressions from First High level Languages. Most Conventions were taken from Mathematics. In PL , Operands , Operators , Parenthesis and function call are part of Arithmetic Expression.
  • 7. Design issues of arithmetic expression What are the operator precedence rules. What are operator Associativity rules. What is the order of Operand Evaluation. Are there restrictions on Operand Evaluation Side effect. Does the Language Allow User-defined operator Overloading. What type mixing is allowed in expression.
  • 8. Operator Evaluation Order Precedence Value on expression may depends on it. a + b * c Operator precedence rules from Mathematicians. Rules almost same for all Imperative languages. U.S => PEMDAS "Please Excuse My Dear Aunt Sally". It stands for "Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction".
  • 9. Why Precedence of Operators Logic by Mathematicians Multiply is based on Addition
  • 10. Unary version of Addition and Subtraction. Unary Addition is called Identity Operator. Input = output , no effect on Operand. Ellis and Storstroup named it as Historical mistake and useless operator. Java and C # has a effect , it coercively change short ,byte to int. C changes it to int type. A + ( - B ) * C is legal but A + - B * C usually is not (legal in C based language)
  • 11. Precedence of Unary Operator -A / B -A * B -A ** B in Ruby ADA, FORTRAN and BASIC ( ** has high precedence) -A ** B Is Equivalent to - ( A ** B )
  • 12. Unary and MOD In Ada , Mod has higher precedence than Unary. - 17 mod 5 Is equivalent to (17 mod 5)
  • 13. What is the difference between Mod and Rem ?
  • 14. APL , has single level precedence for all operators .
  • 15. Associativity a – b + c – d a + b - c When an expression contains two adjacent occurrences of operators with the same level of precedence , the question of which operator is evaluated first is answered by Associativity. Adjacent operators are separated by a single operand with same level of precedence.
  • 16. Exponent Operator Usually from Left to Right Exponentiation is from Right to left (Ruby and FORTRAN) A ** B ** C In Ada ** is non Assosiative A ** B ** C is illegal Use of Parenthesis to do the job In Ada ** is non Assosiative In Visual Basic ^ is for exponentiation and is right associative.
  • 17. Associative rules for imperative languages
  • 18. Single Level Precedence of APL Total Dependency on Associativity Right to Left A X B + C
  • 19. Associativity of Operators Addition , Multiplication mathematically Associative Subtraction and division is not A+B+C order doesn’t matter In Computers This doesn’t hold for floating point arithmetic A+ A –A -A A+A –B –B Suppose A and B are very large numbers Overflow problems and optimization ( C , C++ , ??)
  • 20. Paranthesis Used to alter the precedence and Associativity. Advantage Readability and More control , No need to remember Not good for simple expression Demerit of not using Parenthesis Over complexities
  • 21. Ruby Expressions Pure Object Oriented Programming Every data value , including literal is an object. Ruby supports collection of Arithmetic and Logical operation so C Based Language. But Every thing is implemented as method e.ga+b Overloading of predefined methods (Not recommended) But Useful in some cases Operator overloading for user defined types
  • 22. Conditional Expressions Ternary Operator ?: If – then – else statement If (count == 0 ) Average = 0; Else Average = sum / count; Expression_1 ? Expression_2 : expression_3 Expression_1 is Boolean expression Average = (count ==0 ) ? 0 : sum/count
  • 23. Operand Evaluation Order Expression OPERATOR Expression Variables in expression are evaluated by fetching their values from memory (Constant case may be different) If Expression is paranthesized then all its variables must be evaluated before it can be used as an operand If there is no side effect then the Operand Order is irrelevant Lets look at the Operand Evaluation which has side effects
  • 24. Side Effect A side effect of a function called a functional side effect. A Function changing the global variable By use of Reference variable , Pass by Reference a + fun (a) a + fun(b) Void fun(){ // assuming a is a global variable a }
  • 25. Note : There are not functional side effects in Mathematics There are probably no side effects in pure functional Programming languages Because there context is irrelevant to its meaning
  • 26. Two Possible Solutions to the Problem: 1. Write the language definition to disallow functional side effects No two-way parameters in functions No non-local references in functions Advantage: it works! Disadvantage: Programmers want the flexibility of two-way parameters (what about C?) and non-local references 2. Write the language definition to demand that operand evaluation order be fixed Disadvantage: limits some compiler optimizations
  • 27. Java provides left to right operand evaluation. Ada let you specify the order
  • 28. Overloaded Operators Arithmetic Operators are often used for more than one purpose. + , for integer and float addition , catenation This multiple use of operators is called Operator Overloading Operator Overloading ( Function Overloading )
  • 29. It is acceptable , if readability and reliability is not compromised. & , Address , Bitwise AND , reference Operator. Deterimental to readability and reliabilty E.g x = z & y => x = &y Missing the z will go undetected by compiler.
  • 30. Unary Minus operator (Less Serious) X = z – y => X = - y Distinct Operation not only increase readability but are sometimes convenient to use for common operation as well E.g division operator
  • 31. Sum , count (int) , avg (float) avg = sum / count Integer division Soln: Separate Operator , ( / , div ) Pascal Inferencing on LHS , both operand will coercively converted to float Dynamic Language like php based on the result generate the type Java Script provides only float division.
  • 32. FORTRAN , Ada , C++ , C # , allows the programmer to further overload operator symbol. e.g between scalar and integer array. could overload * whenever For int * int array And for Abstract User defined type . E.g Student.
  • 33. Evaluation When Sensibly used could improve Readability For Matrix Operations A * B + C * D MatrixAdd( MatrixMult(A,B) , MatrixMult(C,D) ) Demerits of Operator Overloading for UDTs Student1 < Student 2
  • 34. Non Overloadable Operators E.g dot . , :: etc Not Taken by Java Taken by C Sharp
  • 35. Type Conversions Narrowing Conversion Convert a value that cannot store all the approximation of original type Double to float ( much higher in java) Widening Conversion Consider as safe but not always Byte to integer Float to double Int to long Exception ( they may result in lost of accuracy) Int to float may loose accuracy upto 2 decimal points
  • 36. Coercion in Expression Mix Mode Expression String + int Int is coerced to be a string Coercion is good or bad Programmer vs compiler Mix Mode expressions are legal in Java int a; float b , c , d; ….. d = b * a; // simply coerced a to float
  • 37. Ada , does not allow much Mix Mode Expression Exception is with the ( ** )Exponential operator. First operand integer/ float Second Operand integer Other exceptions of Mix Mode Expressions in Ada are with subtypes.
  • 38. Byte , short in C based language When used with operator are coerced with int type. A = b + c Utilization of Memory is efficient Handy in large arrays
  • 39. Explicit Type Conversion Both Narrowing and Widening In C based languages it is called Cast. When Narrowing conversion result in significant lose , a warning or error is produced. ( int ) angle Why use brackets (long int ) Ada , Float (sum)
  • 40. Errors in Expression Statically and dynamicaly type checking avoid these problems Limitations of computer arithmetic , mathematical arithmetic. Aritmetic overflow , underflow , divide by zero. Mathemitally disallowed doesn’t mean programmer will not attempt it. Solution: Exception handling in Chapter 14
  • 41. Relational and Boolean Expressions Relational Expression Comparison Operator Value of Relational Operator is Boolean if provided. Simple for arithmetic VS complex for strings 2 < 3 VS abdulvsahad Fortran 95 NE <> Ada /= SQL <> C-Based !=
  • 42. Java script and PHP has two additional operators === and !== == is coercive while === is not “77” == 77 is true VS “77” === 77 is false Ruby == for coercive and eql ? For non coercive Relationa Operators always have low Precedence. A+1 < b * 2
  • 43. Boolean Expression AND OR NOT Exclusive OR Mathematicaly AND and OR are of same precedence so in Ada But not in C , AND has higher precedence ARW -> RE -> BE
  • 44. C has no Boolean type A > b > c Left assosiative A> b is evaluated first and 0 or 1 is returned There is never a comparison of b and c 2<7<1 2<7>1
  • 45. Ruby , Perl { AND , OR , && , || } And , OR have same precedence Spelled version have lower precedence && has higher precedence than ||
  • 46. Arithmetic and Non Arithmetic Operators of C Based Language and at least 14 different level of precedence. Richness of collection of oeprators and complexities of Expressions C , C++ Readability prefer boolean over numeric Coz , numeric is a legal operand to Boolean Operator
  • 47. Short Circuit Evaluation Non Strict Evaluation A Short circuit Evaluation of an expression is one in which the result is determined without evaluating all of the operands and/ or operators E.g (13 * a ) * ( b + c +d * e / 3 ) + (e**d) If a= 0 , then no need to evaluate others ( b + c +d * e / 3 ) + (e**d) * * ( a – b ) If a-b == 0 then result is 1 However This is quite difficult to detect at run time so never taken.
  • 48. Boolean Expression ( a >= 0 ) && (b < 10) Second Expression is independent False AND ? Equals false
  • 49. OR Side effect may occur on complete evaluation Program correctness depends on it. ( a > b) || ( (b++) / 3 ) Order is sometimes not mentioned left or right
  • 50. Ada provides and then or else to specify Shortcircuit Evaluation Index :=1 while ( Index < count ) and then ( array[index] /= key) Loop: Index := index + 1; End loop
  • 51. In C Based Language && and & || and | What are the issues with it ?
  • 52. Assignment One of the central constructs in Imperative languages. Imperative languages are based on von neuman architecture. syntax <target_variable> <assignment_operator> <expression> Most PL use of = as a assignment operator ALGOL 60 introduced := and then Ada followed C may have embedded assignment statements in expression. Fortran and Ada , Assignment can appear as Standalone statement Single target variable
  • 53. Conditional Targets Flag ? count1 : count2 = 0; Equivalent to if ( Flag ) Count1 = 0; else Count 2 = 0;
  • 54. Compound Assignment Operators a = a+b; a += b; Introduced by ALGOL 68 Now in all Imperative languages
  • 55. Unary Assignment Operators Count = count + 1 Count ++; Preceede / follow the operand Sum = ++ count; Count = count + 1 Sum = count Sum = count++; Sum = count Count = count + 1 -count ++ ( when two unary operators to same operand , Association is right to left ) (count ++) // like this Rather than ( - count )++ // not like this
  • 56. Assignment as Expression In C Based Languages , Perl , Javascript Assignment statement generates a result Like a binary operator (but it effects its second operand) if( a= 2){ // true in C , C++ if ( 2 ){ } else{ } Languages which does support , Assignment Operator has less precedence than relational operators If ( ( a=b ) != c ) Without paranthesis it would be If ( ( a= (b != c ) ) // b != c produce 0 or 1
  • 57. Contn’d Side effect of Assignment in Expression Readability Reliability Multiple Assignment Sum = count = 0;
  • 58. List Assignment Perl and ruby provide it ($first , $second , $ third) = (20,40,60); ($first , $second) = ($second , $first) In C Based anguages Int ar[20] = {1,2,3,4,5,6} What If # of variables on R.H.S and L.H.S are mismatched Less and greater cases on R.H.S Ruby has more Elaborate cases
  • 59. Mix Mode Assignment In case of type mismatch , use coercion or not. Fortran , C , C++ and Perl use coercion for mixed mode assignment. Java and C # use coercion for widening conversion is ok and also in some narrowing cases as well e.g int to char if it is in range. Int can be float but not vice verca In All language coerced after RHS expression evaluation One alternative is to coerced all operands to type of LHS Ruby and Python types are associated with objects , so there are no mix mode assignment.
  • 60. Summary Expressions consist of constants , variables , parenthesis , function calls and operators. Assignment statements include target variable , assignment operators and expressions. Semantics of an Expression is determined in large by the order of the evaluation of operators. The Associativity and precedence rules for operators in the expression of a language determine the order of Operator evaluation in those expresion Operand evaluation order is important in functional side effects are possible. Type Conversion can be widening or narrowing . Some narrowing conversion can produced erroneous results. Implicit Conversion or coercion in expressions are common, although they eliminate the error detection benefit of type checking , thus lowering reliability. Assignment statements have appeared in a wide variety of forms , including conditional targets , assigning operators and list assignments.
  • 61. Practices Solve the Problem set given at the end of this chapter. Practice each topic in your Assigned language and favorite language. E.g Ruby , java etc References : Most material other than the text book is taken from Wikipedia.

Hinweis der Redaktion

  1. From Robert W Sebesta , Concept of Programming Languages , 8th Edition
  2. Dividend , Divisor , Sign
  3. We are not talking about the commutative propertyWe mean to say whether value of Expression1 or Expression 2 comes from Memory
  4. Referential Transparency and Side effects
  5. Due to exponent
  6. Optimization + possible Bugs