Data Types and Programming Languages
Document Details

Uploaded by OpulentManganese1434
Tags
Summary
This document covers fundamental concepts in data types, including scalar and composite types, and their implementation in various programming languages. It also delves into arithmetic expressions, operator precedence, and assignment statements, crucial for understanding how programs handle data and perform computations. The content is suitable for students learning programming fundamentals.
Full Transcript
Here is the transcription of the attached images into a structured markdown format: # DATA TYPES MOD. 3A Every program uses data, either explicitly or implicitly, to arrive at a result * Data type: the basic concept of the representation of data in programming languages * Data in its most pri...
Here is the transcription of the attached images into a structured markdown format: # DATA TYPES MOD. 3A Every program uses data, either explicitly or implicitly, to arrive at a result * Data type: the basic concept of the representation of data in programming languages * Data in its most primitive form is simply a collection of ones and zeros also known as bits * Programming languages have a set of simple data entities and mechanisms for creating new ones * Machine dependencies are often part of the application of these concepts * Concept of data limits – in math, the set of integer values are infinite. In hardware, there will always be a largest and smallest number. * Program data can be classified according to their types * Type name represents the possible values that a variable of that type can hold and the way those values are represented internally * Data type (definition 1): a set of values the statement int x; is the same as $x \in Integers$ * Data type (definition 2): a set of values, together with a set of operations on that values having certain properties * A data type is part of mathematical algebra * A data type is a class of data objects with a set of operations for creating and manipulating them. # Specification of data types * Attributes Classify data objects of a given type by Data type and name – does not vary during the lifetime of the object * These can be stored in a descriptor and utilized during the program execution * These are only utilized to establish the storage representation, used explicitly during execution * Values The data type defines the values that a data object of that type could get Typically, they can be a well-ordered set, i.e. it has a least and a greatest value * Operations Define the potential manipulations of of data objects of that type. * Primitive - denoted as part of the language definition * Programmer-defined – they can be represented as subprograms, or class methods An operation is defined by: * Domain - set of probable input arguments * Range - set of potential results * Action - how the result is generated Operation signature Specifies the domain and the range * the number, order and data types of the arguments in the domain, * the number, order and data type of the resulting range mathematical notation for the specification: op name: arg type x arg type x ... x arg type àresult type * The action is specified in the operation implementation. # Sources of ambiguity in operations * Undefined operations for some inputs. * Implicit arguments, e.g. use of global variables * Implicit results - the operation may alter its arguments * Self-modification - typically through change of local data among calls, e.g. random number generators change the seed. # Implementation of a data type * Storage representation * Influenced by the hardware Described in terms of: * Size of the memory blocks required * Layout of attributes and data values within the block * Methods to treat attributes * established by the compiler and not stored in descriptors during execution - C * stored in a descriptor as component of the data object at run time - LISP Prolog * Implementation of operations * Hardware operation direct implementation. E.g. Integer addition * Subprogram/function, e.g. square root operation * In-line code as an alternative of utilizing a subprogram, the code is copied into the program at the point where the subprogram would have been invoked. # ELEMENTARY DATA TYPES MOD. 3A.1 ## A. Scalar Data Types Scalar data types represent a single object, i.e. only one value can be derived. In general, scalar objects follow the hardware architecture of a computer. * Numerical Data Types ### 1. Integers * Specification: Maximal and minimal values * Operations: 1. Arithmetic 2. Relational 3. Assignment 4. Bit operations * Implementation: hardware defined ### 2. Sub -ranges * Specification: subtype of integer * a series of integer values inside some controlled range Example: Pascal declaration A: 1..10 means that the variable A may be assigned integer values from 1 through 10. * Implementation: smaller storage requirements, better type checking ### 3. Floating-point real numbers * Specification: Minimum and maximal value * Round-off issues - the check for equality may fail due to round -off * Implementation: Mantissa - exponent model. Example: $10.5 = 0.105 x 10^2$, Mantissa: 105, Exponent: 2 ### 4. Fixed-point real numbers * Specification: real numbers with predefined decimal places * Implementation : directly supported by hardware or simulated by software * Other Scalar Data Types ### 1. Complex numbers These are software simulated, with two storage locations one the real portion and one for the imaginary portion. ### 2. Rational numbers Can be defined easily as the quotient of two integers, in other terms fractions. ### 3. Enumerations * Example: enum StudentClass {Fresh, Soph, Junior, Senior} the variable StudentClass may accept only one of the four listed values. * Implementation: represented during run time as integers, corresponding to the listed values. ### 4. Booleans * Specification: Two values: true and false. * Can be given explicitly as enumeration Basic operations: and, or, not. * Implementation: A single addressable unit such as byte or word. * Use a bit for the value, e.g. the last bit; 1 - true, O -false. * Use the entire storage; a zero value would then be false, otherwise - true. ### 5. Characters * Specification: Single character as a value of a data object. * Collating sequence - the ordering of the characters, used for lexicographic sorting. Operations: Relational, Assignment, Testing the type of the character - e.g. digit, letter, special symbol. * Implementation: supported by the underlying hardware ## B. Composite Data Types Characterized by a complex data structure organization, processed by the compiler. ### 1. Character Strings * Specification: Fixed declared length : storage allocation at translation time. Strings which are longer than the declared length are truncated. Variable length to a declared bound: storage allocation at translation time. An upper bound for length is set and any string over that length is truncated Unbounded length: storage allocation at run time. String can be any length * Operations: * Concatenation – appending two strings * Relational operations – equal, less than, greater than \*\* Substring selection using positioning subscripts *** Substring selection using pattern matching * Input / output formatting * Implementations: * Fixed declared length: A packed vector of characters * Variable length to a declared bound: a descriptor that contains the maximum length and the current length * Unbounded length: Either a linked storage of fixed-length data objects or a contiguous array of characters with dynamic run-time storage allocation ### 2. Pointers and Programmer- Constructed Objects * Specification: * Reference data objects only of a single type – C, Pascal, Ada. * Reference data objects of any type – Smalltalk * C, C++: pointers are data objects and can be manipulated by the program * Java: pointers are hidden data structures, managed by the language implementation * Implementations: * Absolute addresses stored in the pointer. Enables storing the new object anywhere in the memory * Relative addresses: offset with respect to some base address. ### 3. Files * Usually reside on secondary storage devices as disks, tapes. * Life Cycle is greater than the duration of the program that has created the files. * Implementation – as part of the operating system Types of files ### 1. Sequential file: a data structure composed of a linear sequence of components of the same type. ### 2. Interactive Input-Output: sequential files used in interactive mode. ### 3. Direct Access Files: Any single component can be accessed at random just as in an array. * Key: the subscript to access a component. * Implementation: a key table is kept in main memory ### 4. Indexed Sequential Files: Like direct access files, it uses a key combined with being able to sequentially process the file. The file must be ordered by the key # STRUCTURED DATA TYPES MOD. 3A.2 A data structure is a data object that contains other data objects as its elements or components. ## Mechanisms to create new data types: * Structured data * Homogeneous: arrays, lists, sets, * Non-homogeneous: records * Subprograms * Type declarations – to define new types and operations (Abstract data types) * Inheritance ## Data specifications * Number of components and size * Fixed size – Arrays * Variable size – stacks, lists. Pointer is used to link components. * Type of each component * Homogeneous – all components are the same type * Heterogeneous – components are of different types * Selection mechanism – to identify components – index, pointer * Two-step process: 1. referencing the structure 2. selection of a specific component * Maximum number of components * Organization of the components * Simple linear sequence – arrays, stacks, lists * Multidimensional structures: * separate types (Fortran) * a vector of vectors (C++) ## Operations on data structures * Component selection operations * Sequential * Random * Insertion/deletion of components * Whole-data structure operations * Creation/destruction of data structures ## Implementation of structured data types * Storage representations * storage for the components * Sequential representation * The data structure is stored in a single contiguous block of storage, that includes both descriptor and components. * Used for fixed-size structures, homogeneous structures (arrays, character strings) * Linked representation * The data structure is stored in several noncontiguous blocks of storage, linked together through pointers. * Used for variable-size structured (trees, lists) ## Declarations and type checking for data structures What is to be checked: * Existence of a selected component * Type of a selected component ### Type equivalence and equality of data objects Two questions to be answered: 1. When are two types the same? 2. When do 2 objects have the same value? #### Name equivalence * Two data types are considered equivalent only if they have the same name. * Issues * Every object must have an assigned type, there can be no anonymous types. * A singe type definition must serve all or large parts of a program. #### Structural equivalence * Two data types are considered equivalent if they define data objects that have the same internal components. * Issues * Do components need to be exact duplicates? * Can the field order be different in records? * Can the field sizes vary? ## Data object equality * Two objects are equal if each member in one object is identical to the corresponding member of the other object. * The compiler has no way to know how to compare data values of user-defined type. It is the programmer's role to define that specific data type and to also define the operations with the objects of that type. * This is when type checking happens, as it was discussed in the previous module. * To review * Type checking: checking if each operation performed by a program gets the proper number of arguments of the appropriate data types. Again, * Static type checking is done at compilation. * Dynamic type checking is done at run-time. * Strong typing happens when all type errors can be statically checked * Type inference: implicit data types, used if the interpretation is unambiguous. * Coercion: Implicit type conversion,performed by the system. * Explicit conversion : routines to change from one data type to another. # STRUCTURED DATA TYPES ## 1. Vectors and Arrays * Vector – one dimensional array * Matrix – two-dimensional array * Multidimensional arrays * Slice – a substructure in an array that is also an array, e.g. a column in a matrix * Associative Arrays – elements are selected by a key value * Implementation of array operations * Access – can be implemented efficiently if the length of the components of the array is known at compilation time. * The address of each selected element can be computed using an arithmetic expression. * Whole array operations, e.g. copying an array – may require much memory. ## 2. Records * A record is data structure composed of a fixed number of components of different types. * The components may be heterogeneous, and they are named with symbolic names. * A record is a possibly heterogeneous aggregate of data elements in which the individual elements are identified by names * Design issues: * What is the syntactic form of references to the field? * Are elliptical references allowed * Operations: Assignment is a common operation *if the types are identical * Evaluation and Comparison to Arrays * Access to array elements is much slower than access to record fields, because subscripts are dynamic (field names are static) * Dynamic subscripts could be used with record field access, but it would disallow type checking and it would be much slower * Implementation of Records Offset address relative to the beginning of the records is associated with each field The image appears to be a diagrammatic representation of a 'Record' structure, which is likely from a computer science or programming context. Each segment represents a field within the record, including segments for 'Name', 'Type', and 'Offset', as well as an 'Address' field. ## 3. Lists and Sets * A list is a number of items in an ordered or unordered structure It can be used for several items such as storing objects or deleting and adding objects. But for the programmer to perform the different tasks for the list, the program must have enough memory to keep up with changes done to the list. Different sort of lists includes linear list and linked list. Also, the list can be referred to as an abstract data type. * Lists are a single-dimensional array while a set is a data structure that can store any number of unique values in any order you so wish. Sets are different from arrays in the idea that they only allow non-repeated, unique values within them. * List Operations: * length * emptiness test * head selection * tail selection * concatenation * Set Operations: * Union * Intersection * Cartesian Products ## 4. Executable data objects Data structures which are regarded to be a special type of program statements and all are regarded in the same way (Prolog). # POINTER AND REFERENCE TYPES MOD. 3A.3 * Pointers and References are variables that contain the "address" in memory of a piece of data, rather than the actual data. * Practically applied – or in other words in the real world, let us take your name in the class grade book. Does this name describe the actual you (the physical you-flesh and bones)? NO. Does your name provide information that allows your professor to "refer to" (or reference) you? YES! Can there be multiple names that all refer to you? Of course. The teacher can call you Mr. Doe, your friends can call you, John, and your mom can call you Sweetheart. These names are all "references" to the same data (you J). POINTER Pointers: A pointer is a variable that keeps memory address of another variable. A pointer requires to be de-referenced with * operator to access the memory location it points to. # REFERENCE References : A reference variable is an alias, meaning, it is another name for an already existing variable. A reference, like a pointer, is also applied by saving the address of an object. A reference can be assumed of as a constant pointer (please do not confuse with a pointer to a constant value) with automatic indirection, i.e the compiler will use the * operator for you. Example: int i = 3; // A pointer to variable i (or stores address of i) int *ptr = &i; // A reference (or alias) for i. int &ref = i; (Source: https://www.geeksforgeeks.org/pointers-vs-references-cpp/) # Differences : ## 1. Initialization Pointer initialization: int a = 10; int *p = &a; OR int *p;p = &a; we can declare and initialize pointer at same step or in multiple line. Reference initialization: int a=10;int &p=a; //it is correct but int &p;p=a; // it is incorrect as we should declare and initialize references at single step. (Source: https://www.geeksforgeeks.org/pointers-vs-references-cpp/) ## 2. Reassignment A pointer can be re-assigned. This property is beneficial for application of data structures like linked list, tree, etc. Examples are the following: int a = 5; int b = 6; int *p; p = &a; p = &b; On the other hand, a reference cannot be re-assigned, and should be assigned at initialization. int a = 5; int b = 6; int &p = a; int &p = b; //At this line it will show error as "multiple declaration is not allowed". However it is valid statement, int &q=p; (Source: https://www.geeksforgeeks.org/pointers-vs-references-cpp/) ## 3. Memory Address: A pointer holds its own memory address and size on the stack while a reference shares the same memory address (with the original variable) but also takes up some space on the stack. Kindly note that if we want to know the true address of a reference, it can be found out in turbo IDE by writing the following statement, int &p = a; cout << &(&p); (Source: https://www.geeksforgeeks.org/pointers-vs-references-cpp/) ## 4. NULL value Pointer can be assigned NULL directly, whereas reference cannot. The constraints associated with references (no NULL, no reassignment) ensure that the underlying operations do not run into exception situation. ## 5. Indirection You can have pointers to pointers offering extra levels of indirection. Whereas references only offer one level of indirection.l.e, In Pointers, int a = 10; int *p; int **q; //it is valid. p = &a; q = &p; (Source: https://www.geeksforgeeks.org/pointers-vs-references-cpp/) Whereas in references, int &p = a; int &&q = p; //it is reference to reference, so it is an error. (Source: https://www.geeksforgeeks.org/pointers-vs-references-cpp/) ## 6. Arithmetic operations: Various arithmetic operations can be performed on pointers whereas there is no such thing called Reference Arithmetic.(but you can take the address of an object pointed by a reference and do pointer arithmetic on it as in &obj + 5).) ## When to use What The performances are the same, as references are implemented internally as pointers. But still you can keep some points in your mind to decide when to use what : ### Use references * In function parameters and return types. ### Use pointers: * Use pointers if pointer arithmetic or passing NULL-pointer is needed. For example, for arrays (Note that array access is implemented using pointer arithmetic). * To implement data structures like linked list, tree, etc and their algorithms because to point different cell, we must use the concept of pointers. The following examples can help: In Pointers int arr[] = {10,20,30}; Output: int *p,i ; $p = arr;$ for(i = 0; i<3; i++) { $cout << *p << endl;$ $p++;$ } Source: https://www.geeksforgeeks.org/pointers-vs-references-cpp/ NOTE: The pointer here will be ahead of the base addressLet's take same code in Reference int arr[] = {10,20,30}; Output: int &p = arr[0]; int i; for(i = 0; i<3; i++) { $cout << p << endl;$ $p++; //here it will increment arr[0]++$ } (Source: https://www.geeksforgeeks.org/pointers-vs-references-cpp/) NOTE: The pointer here will be at base address only. # Expression and Assignment Statements MOD. 3B Image of a code with lines of text against a dark background. Image of lines of codes against a dark background. Image of computer screen with codes and texts in white color. Why is studying these important? * Expressions are the fundamental means of specifying computations in a programming language * To understand expression evaluation, need to be familiar with the orders of operator and operand evaluation * Essence of imperative languages is dominant role of assignment statements ## ARITHMETIC EXPRESSIONS MOD. 3B.1 * Their calculation was one of the reasons for the development of the first programming languages. * Most of the attributes of arithmetic expressions in programming languages were inherited from principles that evolved in mathematics. * Arithmetic expressions consist of operators, operands, parentheses, and function calls. * The operators can be unary, or binary. C-based languages include a ternary operator, which has three operands (conditional expression). * The objective of an arithmetic expression is to specify an arithmetic computation. * An implementation of such a computation must cause two actions:* * Fetching the operands from memory Executing the arithmetic operations on those operands. #### 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. What mode mixing is allowed in expressions? ### Operator Evaluation Order 1. Precedence * The operator precedence rules for expression evaluation define the order in which “adjacent” operators of different precedence levels are evaluated (“adjacent” means they are separated by at most one operand). * Typical precedence levels: 1. parentheses 2. unary operators 3. `**` (if the language supports it)` 4. `*/` 5. `+,- ` * Many languages also include unary versions of addition and subtraction. * Unary addition (+) is called the identity operator because it usually has no associated operation and thus has no effect on its operand. * In Java, unary plus actually does have an effect when its operand is short or byte. An implicit conversion of short and byte operands to int type takes place. * Unary minus operator (-) Ex: A + (- B) * C // is legal A + - B * C // is illegal 2. ***Associativity*** * The operator associativity rules for expression evaluation define the order in which adjacent operators with the same precedence level are evaluated. An operator can be either left or right associative. * Typical associativity rules: * Left to right, except `**`, which is right to left **Sometimes unary operators associate right to left (e.g., FORTRAN)** Ex: (Java) a - b + c // left to right Ex: (Fortran) A `**` B `**` C // right to left (A `**` B) `**` C // In Ada it must be parenthesized | Language | Associativity Rule | | ------------- |:-------------:| | FORTRAN | Left: `*/+-`<br>Right: `**` | | C-BASED LANGUAGES | Left: `* / % binary binary: +-`<br>Right: ++ `--unary`--unary + | | ADA | Left: all except `**`<br>Non-associative: `**` | ***Source:*** https://www2.southeastern.edu/Academics/Faculty/kyang/2014/Fall/CMPS401/ClassNotes/CMPS401ClassNotesChap07.pdf * APL is different; all operators have equal precedence and all operators associate right to left. **Example:** A X B + C // A = 3, B = 4, C = 5 à27 * Precedence and associativity rules can be overridden with parentheses. * ***Parentheses*** * Programmers can alter the precedence and associativity rules by placing parentheses in expressions. * A parenthesized part of an expression has precedence over its adjacent un-parenthesized parts. * Example: (A + B) * C ***Source:*** https://www2.southeastern.edu/Academics/Faculty/kyang/2014/Fall/CMPS401/ClassNotes/CMPS401ClassNotesChap07.pdf ### 3. ***Conditional Expressions*** * Sometimes if-then-else statements are used to perform a conditional expression assignment if (count == 0) average = 0; else average = sum / count; Source: https://www2.southeastern.edu/Academics/Faculty/kyang/2014/Fall/CMPS401/ClassNotes/CMPS401ClassNotesChap07.pdf * In the C-based languages, this can be specified more conveniently in an assignment statement using conditional expressions. Note that ? is used in conditional expression as a ternary operator (3 operands). `expression_1? expression_2 : expression_3` * Example: average = (count == 0) ? 0 : sum / count; ### 4. ***Operand evaluation order*** The process: 1. Variables: just fetch the value from memory. 2. Constants: sometimes a fetch from memory; sometimes the constant is in the machine language instruction. 3. Parenthesized expressions: evaluate all operands and operators first. # OVERLOADED OPERATORS MOD. 3B.2 * The use of an operator for more than one purpose is operator overloading. * Some are common (e.g., + for int and float). * Java uses + for addition and for string concatenation. * Some are potential trouble (e.g., & in C and C++)* $x = &y // as binary operator bit-wise logical$ // AND, as unary it is the address of y - Causes the address of y to be placed in x. - Some loss of readability to use the same symbol for two completely unrelated operations. - The simple keying error of leaving out the first operand for a bit-wise AND operation can go undetected by the compiler "difficult to diagnose”. - Can be avoided by introduction of new symbols (e.g., Pascal's div for integer division and / for floating point division) ### Type Conversions * A narrowing conversion is one that converts an object to a type that cannot include all of the values of the original type e.g., double to float. * A widening conversion is one in which an object is converted to a type that can include at least approximations of all the values of the original type e.g., int to float.** ** ## ***Coercion in Expressions*** * A mixed-mode expression has operands of different types. * A coercion is an implicit type conversion. * The disadvantage of coercion: * They reduce in the type error detection ability of the compiler * In most languages, all numeric types are coerced in expressions, using widening conversions * Languages do not agree on the issue of coercion in arithmetic expressions. * Those against a broad range of coercion are concerned with the reliability problems that can result from such coercion, because they eliminate the benefits of type checking. * Those who would rather include a wide range of coercion are more concerned with the loss in flexibility that results from restrictions. * The question of whether programmers must be concerned with this category of errors or whether the compiler should detect them. Java method Example: void mymethod() { int a, b, c; float d; ... a = b * d; ... } * Assume that the second operand was supposed to be c instead of d. * Because mixed-mode expressions are legal in Java, the compiler would * not detect this as an error. Simply, b will be coerced to float. ### ***Explicit Type Conversions*** * Often called casts in C-based languages. * Examples: Ada: FLOAT(INDEX)--INDEX is INTEGER type Java: (int)speed /*speed is float type*/ * Errors in Expressions Caused by: * Inherent limitations of arithmetic e.g. division by zero * Limitations of computer arithmetic e.g. overflow or underflow * Floating-point overflow and underflow, and division by zero are examples of run-time errors, which are sometimes called exceptions. # RELATIONAL AND BOOLEAN EXPRESSIONS MOD. 3B.3 ### Relational Expressions * A relational operator: an operator that compares the values of its tow operands. * Relational Expressions: two operands and one relational operator. * The value of a relational expression is Boolean, unless it is not a type included in the language. * Use relational operators and operands of various types. * Operator symbols used vary somewhat among languages (!=, /=,.NE., <>, #) * The syntax of the relational operators available in some common languages is as follows: | Operation | Ada | C-Based Languages | Fortran 95 | | ---- | ---- | ---- | ---- | | Equal | `=` | `==` |`.EQ. or ==` | | Not Euqal | `/=` | `!=` |`.NE.` | | Greater than | `>` | `>` |`.GT. or >` | |Less than| `<` | `<` |`.LT. or <` | |Greater than or equal | `>=` | `>=` |`.GE. or >=` | |Less than or equal | `<=`| `<=` |`.LE. or <=` | ### Boolean Expressions * *Operands are Boolean and the result is Boolean. | FORTRAN 77 | FORTRAN 90 | C | Ada | | :----: | :----: | :----:| :----:| |` .AND.` |` and `|`&&` |`and`| |`.OR.` |` or `|`||` |`or`| |`.NOT.` |` not `|`! `|`not` | * Versions of C prior to C99 have no Boolean type; it uses int type with O for false and nonzero for true. * One odd characteristic of C's expressions:* * a < b < c is a legal expression, but the result is not what you might expect. * The left most operator is evaluated first because the relational operators of C, are left associative, producing either 0 or 1. * Then this result is compared with var c. There is never a comparison between b and c. # SHORT CIRCUIT EVALUATION MOD. 3B.4 * A short-circuit evaluation of an expression is an operation where the result is determined without evaluating all of the operands and/or operators. Written below is an example:** ``` (9* a)\* (b/9– 1) // is independent of the value (b/9-1) if a = 0, because 0*x = 0. ``` So when a = 0, there is no need to evaluate (b/9- 1) or perform the second multiplication. * However, this shortcut is not easily detected during execution, so it is never taken. * The value of the Boolean expression: * (a >= 0) && (b < 10) // is independent of the second expression if a < 0, because(F && x) is False for all the values of x. * Short-circuit evaluation exposes the potential problem of side effects in expressions (a > b) || (b++ / 3) // b is changed only when a <= b. * If the programmer assumed b would change every time this expression is evaluated during execution, the program will fail. * C, C++, and Java: use short-circuit evaluation for the usual Boolean operators (&`&` and `||`), but also provide bit-wise Boolean operators that are not short circuit (& and |) # ASSIGNMENT STATEMENTS MOD. 3B.5 ### Simple Assignments * The C-based languages use `==` as the equality relational operator to avoid confusion with their assignment operator. * The operator symbol for assignment: 1. FORTRAN, BASIC, PL/I, C, C`++`, Java 2. := ALGOL, Pascal, Ada Conditional Targets ### Example * flag ? count 1 : count2 = 0; if (flag) count1 = 0; else count2 = 0; ### Compound Assignment Operators * A compound assignment operator is a shorthand method of stipulating a commonly needed form of assignment. * The form of assignment that can be abbreviated with this technique has the destination var also appearing as the first operand in the expression on the right side, as in a = a + b * The syntax of assignment operators that is the concatenation of the desired binary operator to the = operator. sum += value; ⇔ sum = sum + value; * C-based languages consist of two special unary operators that are actually abbreviated assignments. * They merge increment and decrement operations with assignments *The operators `++` and `--` can be used either in expression or to form standalone single-operator assignment statements. They can appear as prefix operators: ` sum = ++ count; ⇔ count = count + 1; sum = count; `* If the same operator is used as a postfix operator: ` sum = count ++; ⇔ sum = count; count = count + 1`" ### Assignment as an Expression * This design treats the assignment operator much like any other binary operator, except that it has the side effect of changing its left operand. * Example: ``` while ((ch = getchar())!=EOF) {...} // why () around assignment? ```` * The assignment statement must be parenthesized because the precedence of the assignment operator is lower than that of the relational operators. * Disadvantage: * Another kind of expression side effect which leads to expressions that are difficult to read and understand. * For example a = b + (c = d / b++) – 1 denotes the instructions * Assign b to temp * Assign b + 1 to b * Assign d / temp to c * Assign b + c to temp * Assign temp – 1 to a * There is a loss of error detection in the C design of the assignment operation that frequently leads to program errors ``` If (x = y) ... instead of If (x == y) ... ``` ###. *Mixed-Mode Assignment * In FORTRAN, C, and C++, any numeric value can be assigned to any numeric scalar variable; whatever conversion is neccessary is done. * In Pascal, integers can be assigned to reals, but reals cannot be assigned to integers (the programmer must specify whether the conversion from real to integer is truncated or rounded.) * In Java, only widening assignedment coercion are done. * In Ada, there is no assignedment coercion. *In all languages that allow mixed-mode assignment, the coercion takes place only after the right-side expression