Chapter 7
7.1 – Introduction
(Paraphrased clearly for beginners in Google Docs–ready format)
What Is This Chapter About?
This chapter covers two major programming topics:
Expressions
Assignment Statements
Why Expressions Matter
Expressions are the main way to perform calculations in programming.
Every programmer should understand:
How expressions are written (syntax)
What they mean and how they behave (semantics)
Syntax vs. Semantics
Syntax: The structure or form of the expression
(Example: a+b*c )
Semantics: The meaning and behavior of the expression
(Example: How values are calculated based on rules like operator
precedence)
Important Concepts Covered in This Chapter
1. Order of Evaluation
Which operator is processed first in a complex expression?
2. Operand Evaluation Order
If an expression has multiple variables or function calls, in what order
are they evaluated?
Chapter 7 1
3. Side Effects
What happens if evaluating a function also changes a variable?
4. Overloaded Operators
Can an operator (like + ) work on multiple types like numbers and
strings?
5. Mixed-Mode Expressions
What happens when you mix data types (like int + float )?
6. Type Conversions
How does the program handle changing one data type into another?
7. Relational and Boolean Expressions
Expressions that compare values or use logical operations (like AND ,
OR )
8. Short-Circuit Evaluation
Can the result be decided early without evaluating the whole
expression?
9. Assignment Statements
Statements that store values into variables (like x=5 )
Assignments in Imperative vs. Functional Languages
🔸 Imperative Languages (C, Java, etc.)
Assignments are central to the language.
Variables change value over time.
Assignments have side effects (they modify program state).
🔸 Functional Languages (Haskell, ML, etc.)
Variables are more like named values or parameters.
Values do not change — assignments are just definitions.
These "assignments" do not cause side effects.
Chapter 7 2
7.2 Arithmetic Expressions
What Is an Arithmetic Expression?
An arithmetic expression is a combination of:
Operators (like + ,,, / )
Operands (like variables, constants, or literals)
Parentheses (to group parts of the expression)
The expression is evaluated to produce a numeric value.
✅ Examples:
a+b*c
(x + y) / 2
7.2.1 Operators
✅ Types of Arithmetic Operators
Most programming languages support these basic operators:
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
** Exponentiation (in some languages like Python)
% Modulus (remainder, in C-like languages)
7.2.2 Operator Precedence and Associativity
✅ What Is Operator Precedence?
Chapter 7 3
Precedence determines the order in which operations are performed when
there are multiple operators.
Operators with higher precedence are evaluated first.
✅ What Is Associativity?
Associativity decides the direction of evaluation when operators have the
same precedence.
Associativity Type Direction
Left-associative Evaluate left to right (like + , - )
Right-associative Evaluate right to left (like ** )
✅ Example:
a+b*c
Multiplication has higher precedence, so b*c is evaluated first.
✅ Parentheses Override Precedence
You can control evaluation order using parentheses.
(a + b) * c
a+b is done before multiplication, even though normally has higher
precedence.
7.2.3 Operand Evaluation Order
✅ In What Order Are Operands Evaluated?
In some expressions, the order in which operands are evaluated affects
the result — especially if there are function calls or side effects.
✅ What Are Side Effects?
Chapter 7 4
A side effect happens when evaluating an operand changes something
else in the program (like modifying a variable or doing input/output).
Example:
x = 1;
a = (x++) + (x++);
The value of a depends on which (x++) is evaluated first.
⚠️ Not All Languages Define Operand Order
In C and C++, the order of evaluation for some expressions is not fixed — it
may vary between compilers.
In Java and Python, operand evaluation order is usually left to right.
7.3 Overloaded Operators
What Does "Overloaded Operator" Mean?
An overloaded operator is an operator (like + , , or ) that is allowed to work
with more than one data type.
The operator’s behavior changes depending on the types of the operands.
✅ Simple Example:
int a = 5, b = 3;
float x = 2.5, y = 1.5;
a+b → integer addition
x+y → floating-point addition
In both cases, the operator + is used, but it behaves
differently depending on the type of the operands.
Chapter 7 5
7.3.1 Operator Overloading in Programming
Languages
✅ Widespread Use of Overloading
Many languages allow built-in operators (like + , , , etc.) to be used with
multiple types.
This type of overloading is called built-in operator overloading.
Common Overloaded Operators:
Operator Typical Uses
+ Add integers, floats, strings (in some languages)
- Subtract numbers
* Multiply numbers, repeat strings/lists (Python)
/ Divide integers or floats
== Compare numbers, strings, or objects
✅ Examples in Different Languages
🔹 Python:
print(3 + 4) # integer addition
print("hi" + "bye") # string concatenation
🔹 Java:
System.out.println(3 + 4); // 7
System.out.println("hi" + "bye"); // "hibye"
🔹 C++:
C++ also allows custom operator overloading, where programmers can
define how an operator works for user-defined types (like classes).
Chapter 7 6
class Complex {
public:
int real, imag;
Complex operator + (const Complex& other) {
Complex result;
result.real = real + other.real;
result.imag = imag + other.imag;
return result;
}
};
7.3.2 Risks of Overloading
✅ Advantages:
Makes code simpler and more readable
You can use familiar operators for new types (like vectors or complex
numbers)
❌ Disadvantages:
Too much overloading can make code confusing
The same operator might do very different things, which can lead to
unexpected behavior
It can also make debugging harder
7.3.3 Should All Operators Be Overloadable?
Some languages limit which operators can be overloaded.
Others allow almost all operators to be redefined.
✅ Language Comparison:
Language Overloading Allowed?
C ❌ No user-defined operator overloading
Chapter 7 7
Language Overloading Allowed?
C++ ✅ Yes, very flexible
Java ❌ No user-defined overloading (only built-in)
Python ✅ Yes, for built-in types and custom classes
Ada ✅ Allows limited overloading
7.4 Type Conversions
What Is Type Conversion?
A type conversion happens when a value of one data type is converted
into another type.
This often happens in expressions where operands have different types
(like int and float ).
✅ Example:
int a = 5;
float b = 2.5;
float result = a + b; // a is automatically converted to float
Here, a becomes 5.0 temporarily so it can be added to 2.5 .
7.4.1 Coercion
✅ What Is Coercion?
Coercion is an automatic (implicit) type conversion done by the compiler
or interpreter.
You don’t have to write extra code — the system figures it out.
✅ Example:
int x = 3;
float y = 3.5;
Chapter 7 8
float z = x + y; // x is coerced to float
✅ Language Examples of Coercion
Language Supports Coercion? Notes
C/C++ ✅ Yes Widely used, but can cause bugs
Java ✅ Yes Safe coercion (e.g., int → float )
Python ✅ Yes Dynamically handles mixed types
Pascal ❌ No Forces explicit type conversion
7.4.2 Explicit Type Casting (Manual Conversion)
✅ What Is Casting?
Casting is when the programmer manually converts one type into another.
You use special syntax to tell the compiler exactly what you want.
✅ Example in C:
int a = 5;
float b = (float)a; // a is explicitly cast to float
✅ Why Use Casting?
To avoid unexpected behavior
To control precision
To ensure compatibility between types
✅ Java Example:
double x = 9.75;
int y = (int)x; // y becomes 9 (decimal part is lost)
Chapter 7 9
7.4.3 Mixed-Mode Expressions
✅ What Are Mixed-Mode Expressions?
These are expressions where multiple types are involved, like:
int a = 4;
float b = 2.0;
float result = a + b;
In such cases:
The narrower type (int) is promoted to the wider type (float) to
perform the operation.
✅ Order of Promotion
Type Promotion (Typical Order)
char
int
float
double
❌ Risks of Mixed-Mode Expressions
Loss of data: e.g., converting float → int drops decimal part.
Unpredictable results in complex expressions, especially with coercion.
Chapter 7 10
✅ Best Practices
Avoid mixing too many types in one expression.
Use explicit casting when needed for clarity and safety.
7.5 Relational and Boolean Expressions
What Is a Relational Expression?
A relational expression compares two values and produces a Boolean
result ( true or false ).
These expressions are also called comparison expressions.
✅ Common Relational Operators
Operator Meaning Example Result
== Equal to 5 == 5 true
!= Not equal to 4 != 5 true
< Less than 3<5 true
<= Less than or equal to 5 <= 5 true
> Greater than 6>3 true
>= Greater than or equal 7 >= 8 false
✅ Example:
int a = 10, b = 20;
bool result = (a < b); // true
What Is a Boolean Expression?
A Boolean expression is an expression that produces a Boolean value: true
or false .
These expressions may include:
Relational operators
Chapter 7 11
Logical (Boolean) operators
Boolean Operators (Logical Operators)
✅ Basic Boolean Operators
Operator Meaning Example Result
&& Logical AND true && false false
` ` Logical OR
! Logical NOT !true false
✅ Truth Table for AND ( && )
A B A && B
true true true
true false false
false true false
false false false
✅ Truth Table for OR ( || )
A B A || B
true true true
true false true
false true true
false false false
✅ Truth Table for NOT ( !)
A !A
true false
false true
Chapter 7 12
Language Notes on Boolean and Relational
Expressions
✅ C and C++
The result of a relational expression is an integer:
0 → false
Any non-zero value → true
No built-in bool type in early C (added later in C99)
✅ Java
Has a true Boolean type ( boolean )
Results of relational and Boolean expressions are strictly true or false
✅ Python
Uses True and False (capitalized)
All non-zero values are truthy, 0 and None are falsy
Combining Relational and Boolean Expressions
✅ Example:
int x = 10, y = 20;
if (x < y && y < 30) {
// condition is true
}
You can combine relational checks using && and ||
7.6 Short-Circuit Evaluation
What Is Short-Circuit Evaluation?
Chapter 7 13
Short-circuit evaluation is a technique used in Boolean expressions.
It means that the second part of the expression is only evaluated if
needed.
✅ Why Is It Called “Short-Circuit”?
Like an electrical short circuit — it stops early when the result is already
known.
How It Works
✅ Logical AND ( && )
In an expression like:
A && B
If A is false, then B is not evaluated.
Because false && anything is always false .
✅ Logical OR ( || )
In an expression like:
A || B
If A is true, then B is not evaluated.
Because true || anything is always true .
Example (in C, C++, Java, Python):
if (x != 0 && (10 / x > 1)) {
// safe: division only happens if x is not zero
}
If x == 0 , the first condition is false, so the division is skipped.
Chapter 7 14
This avoids a divide-by-zero error.
Why Is Short-Circuit Evaluation Useful?
✅ Benefits:
1. Improves Efficiency
Doesn’t waste time evaluating unnecessary expressions.
2. Prevents Errors
Avoids operations that would crash (like dividing by zero or null pointer
access).
3. Lets You Control Flow
Used in programming logic to test conditions safely.
Short-Circuit Behavior in Languages
Supports Short-Circuit
Language Notes
Evaluation?
C / C++ ✅ Yes Default for && and `
Java ✅ Yes && and `
Python ✅ Yes and and or behave this way
Ada ❌ Not by default Has separate operators for short-
circuit
❗ Ada Special Case:
Ada has both short-circuit and full-evaluation operators.
Operator Meaning
and then Short-circuit AND
or else Short-circuit OR
and , or Full evaluation versions
7.7 Assignment Statements
Chapter 7 15
What Is an Assignment Statement?
An assignment statement is used to give a value to a variable.
It connects a name (the variable) with a value or result of an expression.
✅ General Format:
variable = expression
The expression is evaluated, and its result is stored into the variable.
✅ Example:
x = 3 + 4; // x gets the value 7
Assignment in Imperative Languages
In languages like C, Java, Python, assignment is a core concept.
Variables can be assigned multiple times — they change throughout the
program.
✅ C/C++/Java Example:
int x;
x = 5;
x = x + 1; // x becomes 6
Assignment in Functional Languages
In purely functional languages (like Haskell or ML), variables are not
mutable.
Once a name is assigned a value, it cannot be changed — it's like a named
constant.
Chapter 7 16
✅ Functional Language Behavior:
x=5
-- x cannot be reassigned to a different value
Functional languages avoid side effects and state changes.
Multiple Assignments
✅ Chained Assignment
Some languages support assigning multiple variables at once:
a=b=c=0
All three variables get the value 0 .
✅ Parallel Assignment
In some languages (like Python), you can assign multiple values at the
same time:
a, b = 1, 2
a becomes 1 , b becomes 2 .
Assignment as an Expression
In languages like C and C++, assignment statements can also be used as
expressions that return a value.
✅ Example:
x = (y = 5); // y is set to 5, then x is set to 5
This allows assignments to be used inside larger expressions.
Chapter 7 17
⚠️ Risk:
Can make code hard to read or debug, especially if chaining assignments.
Compound Assignment Operators
Many languages provide shortcuts for assignment combined with
arithmetic.
✅ Common Operators:
Operator Meaning Example Equivalent To
+= Add and assign x += 2 x=x+2
-= Subtract and assign y -= 3 y=y-3
*= Multiply and assign z *= 5 z=z*5
/= Divide and assign a /= 4 a=a/4
Assignment Statement Summary
Assignment is used to store values into variables.
Different languages have different rules about how assignment works:
Imperative languages: allow reassignment and side effects.
Functional languages: treat assignment as unchangeable definitions.
7.8 Mixed-Mode Assignment
What Is Mixed-Mode Assignment?
A mixed-mode assignment happens when you assign a value of one data
type to a variable of another data type.
✅ Example:
int x;
float y = 3.5;
Chapter 7 18
x = y; // assigning a float to an int
In this case, the value of y (which is a float) is converted into an integer
before it is stored in x .
So x will get the value 3 (the decimal .5 is lost).
How Does Type Conversion Happen in
Assignment?
Most languages automatically perform type conversion when needed.
This automatic conversion is called coercion.
Risks in Mixed-Mode Assignments
❌ Potential Problems:
1. Loss of Precision
Converting from float → int removes the fractional part.
2. Unexpected Behavior
Some conversions might round down or truncate values, which can
affect logic.
3. Language Differences
Different programming languages may handle coercion differently,
which could lead to bugs if not understood.
✅ Example in Java:
int a;
double b = 7.9;
a = (int) b; // manual casting: a gets 7
Here, the cast is explicit, so the programmer is clearly asking for a type
conversion.
Chapter 7 19
Type Conversion Rules Vary by Language
✅ Some Language Behaviors:
Mixed-Mode Assignment
Language Automatic or Manual?
Allowed?
C/C++ ✅ Yes Usually automatic, can also be explicit
Java ✅ Yes Requires explicit casting for narrowing
conversions
Python ✅ Yes Dynamic typing handles it at runtime
Pascal ❌ No Requires matching types exactly
Fortran ✅ Yes Automatically converts between
numeric types
Best Practices
✅ What Should Programmers Do?
1. Use explicit casting when needed, so that the code is clear.
2. Be aware of precision loss in float → int conversions.
3. Avoid unnecessary type mixing in assignments when possible.
4. Always check how your chosen language handles coercion.
✅ Summary
Mixed-mode assignment involves storing a value of one type into a
variable of another type.
This may involve automatic or manual type conversion.
You should always be careful when mixing types to avoid logic errors.
7.9 Type Evaluation
What Is Type Evaluation?
Chapter 7 20
Type evaluation is the process of figuring out the type of an expression or
variable.
It helps the compiler (or interpreter) know:
How much memory is needed
Which operations are allowed
What rules to apply when different types interact
✅ Why Is It Important?
The correct type affects:
The result of operations
The efficiency of code
Whether the code will run or produce an error
When Does Type Evaluation Happen?
✅ Static Type Systems
In statically typed languages (like C, Java, Ada), type evaluation happens
at compile time.
This allows:
Early error detection
More efficient code generation
✅ Dynamic Type Systems
In dynamically typed languages (like Python, JavaScript), type evaluation
happens at runtime.
This allows:
More flexibility
But also more chance of runtime errors
How Is Type Determined?
Chapter 7 21
✅ For Simple Variables
The type is either:
Declared explicitly by the programmer
int x; // x is an integer
Or inferred by the compiler (in languages with type inference)
x=5 # Python decides x is an int
✅ For Expressions
The type depends on:
The types of operands
The operators used
Example:
int a = 3;
float b = 2.5;
float c = a + b; // a is promoted to float; result is float
The type of a+b is float, because the int is converted.
Type Checking and Type Errors
✅ Type Checking
Type evaluation is closely related to type checking, where the compiler
ensures that:
You are using the right types in operations
The types match in assignments or function calls
❌ Type Errors Happen When:
Chapter 7 22
You try to combine incompatible types, such as:
int x = "hello"; // Error: cannot assign string to int
Language Support for Type Evaluation
Type Evaluation
Language Notes
Style
C/C++ Static Types must be declared or inferred by context
Uses strong typing; types are known at
Java Static
compile time
Python Dynamic Type is evaluated when code runs
Haskell Static with inference Compiler figures out types automatically
JavaScript Dynamic Loose typing; type evaluation at runtime
✅ Type Evaluation in Type Inference Systems
Some languages (like Haskell, ML, Rust) have advanced type inference:
The compiler automatically figures out the types based on usage
You don’t need to write the types explicitly
Chapter 7 23