Compiler Design
Chapter 03: Intermediate Code & Types – Syntax-Directed Translation, Three Address Code, Type Checking, and Overloading.
Deep dive into the crucial intermediate representation and type management phases of compiler design.
Categories of all notesπ Topic: Syntax-Directed Translation and Syntax-Directed Translation Schemes
What is Syntax-Directed Translation (SDT)?
English: Syntax-Directed Translation is a technique where translation of a programming language construct is driven by its syntax structure. Each grammar rule is associated with actions that help translate input into output (like converting source code to intermediate code).
Hinglish: Syntax-Directed Translation matlab jab hum programming language ke syntax rules ke saath kuch actions attach karte hain, jisse source code ko translate ya convert kiya jata hai (jaise machine code, intermediate code).
5 Key Points about SDT
- π‘ Each production rule in grammar is linked with semantic actions (code or instructions).
- π‘ Translation happens during parsing using these actions.
- π‘ Helps generate intermediate code or target code from source code.
- π‘ It ties syntax (grammar) with translation steps.
- π‘ Used in compilerβs syntax-directed translation phase.
What is Syntax-Directed Translation Scheme (SDTS)?
English: A Syntax-Directed Translation Scheme is a context-free grammar augmented with rules (semantic actions) to specify translation.
Hinglish: Syntax-Directed Translation Scheme ek grammar hai jisme har rule ke saath translation instructions attach hote hain, jisse code ka translation define hota hai.
Components of SDTS
- Grammar (CFG) rules
- Semantic rules or actions (attached to grammar rules)
- Attributes (values computed during parsing)
Example of SDTS
Suppose we have a simple grammar for arithmetic expressions:
E β E + T { E.val = E.val + T.val }
E β T { E.val = T.val }
T β id { T.val = lookup(id) }
Here:
{ ... }
are semantic actions.E.val
andT.val
are attributes storing values of expressions and terms.- When parsing
E β E + T
, we compute the value by adding left and right parts.
Types of Attributes
- Synthesized Attributes: Computed from child nodes up to parent node.
- Inherited Attributes: Computed from parent or sibling nodes down to child nodes.
Summary in Hinglish
- SDT me hum grammar ke rules ke sath translation instructions attach karte hain.
- SDTS ek aisa grammar hota hai jisme semantic actions bhi hoti hain.
- Ye compiler me source code ko intermediate ya target code me translate karne me help karta hai.
- Attributes ke through values ya properties compute hote hain.
Suggested Diagram
Grammar Rules + Semantic Actions β Syntax-Directed Translation Scheme (SDTS)
β
Parsing + Action Execution β Translation of Source Code
β
Intermediate/Target Code Generation
π Topic: Intermediate Code
Definition of Intermediate Code
English: Intermediate Code is a middle-level representation of source code generated by a compiler after syntax analysis and before generating the final machine code. It is easier to translate into machine code and helps optimize programs.
Hinglish: Intermediate Code matlab source code ka ek aisa beech ka roop jo compiler syntax analysis ke baad banata hai aur final machine code banane se pehle use karta hai. Yeh code machine code me convert karna aasan hota hai.
5 Important Points about Intermediate Code
- π‘ Intermediate code is machine-independent β it is not tied to any specific hardware.
- π‘ It acts as a bridge between source code and machine code.
- π‘ Facilitates optimization of code before final translation.
- π‘ Helps make compilers portable across different machines.
- π‘ Commonly used intermediate representations include three-address code, syntax trees, and postfix notation.
Why use Intermediate Code?
- Direct translation from source code to machine code is complex.
- Intermediate code allows compilers to separate front-end and back-end parts.
- Makes optimization easier and more effective.
- Helps in supporting multiple target machines using the same front-end.
Types of Intermediate Code
Type | Description | Example |
---|---|---|
Three-Address Code (TAC) | Each instruction has at most 3 addresses (operands). | t1 = a + b |
Syntax Tree | Tree representation showing the hierarchical structure. | Expression tree of (a + b) * c |
Postfix Notation | Operators follow operands, easy for stack-based evaluation. | a b + c * |
Quadruples | Instruction with 4 fields: op, arg1, arg2, result. | (+, a, b, t1) |
Triples | Similar to quadruples but without result field. | (+, a, b) |
Example of Three-Address Code
Expression: a = b + c * d
Possible TAC:
t1 = c * d
t2 = b + t1
a = t2
Advantages of Intermediate Code
- π Simplifies machine code generation.
- π Easier to perform optimizations like dead code elimination, constant folding.
- π Makes compiler modular (front-end, middle-end, back-end).
- π Improves portability of compilers.
- π Facilitates code analysis.
Disadvantages of Intermediate Code
- π Requires extra memory to store intermediate code.
- π Additional step may increase compilation time slightly.
- π Needs design of intermediate representation carefully.
Summary in Hinglish
- Intermediate code source code aur machine code ke beech ka code hota hai.
- Yeh machine independent hota hai aur compiler ko optimize karne mein help karta hai.
- Three-address code sabse popular intermediate representation hai.
- Intermediate code compiler ko modular aur efficient banata hai.
Suggested Diagram
Source Code
β
Syntax Analysis
β
Intermediate Code Generation
β
Optimization
β
Machine Code Generation
π Topic: Postfix Notation (Reverse Polish Notation)
Definition of Postfix Notation
English: Postfix Notation is a way of writing arithmetic expressions where the operator comes after the operands. It is also called Reverse Polish Notation (RPN).
Hinglish: Postfix Notation ek tarika hai jisme operator apne operands ke baad likha jata hai. Isse Reverse Polish Notation bhi kehte hain.
How is Postfix different from Infix?
Infix (Normal) | Postfix (RPN) |
---|---|
Operator between operands | Operator after operands |
Example: A + B | Example: A B + |
Needs parentheses sometimes | No parentheses needed |
5 Important Points about Postfix Notation
- π‘ No need for parentheses to specify order of operations.
- π‘ Easier for computers to evaluate expressions.
- π‘ Evaluation can be done using stack data structure.
- π‘ Commonly used in compilers and calculators.
- π‘ Helps in generating intermediate code.
Example: Infix to Postfix Conversion
Convert infix expression (A + B) * C
to postfix:
Infix: (A + B) * C
Postfix: A B + C *
Step-by-step Evaluation of Postfix Expression
Evaluate: 2 3 4 * +
- Push 2 onto stack.
- Push 3 onto stack.
- Push 4 onto stack.
- Encounter
*
operator: Pop 4 and 3, multiply β 12. Push 12. - Encounter
+
operator: Pop 12 and 2, add β 14. Push 14.
Result: 14.
Advantages of Postfix Notation
- π No need to remember operator precedence rules.
- π Easier and faster to evaluate by machines.
- π Simple algorithm using stacks for evaluation.
- π Eliminates ambiguity in expressions.
Disadvantages of Postfix Notation
- π Not easy for humans to read or write compared to infix.
- π Needs conversion from infix before evaluation in many cases.
Summary in Hinglish
- Postfix notation me operator operands ke baad likha jata hai.
- Isme parentheses ki zarurat nahi hoti.
- Yeh computer ke liye expressions ko evaluate karna aasaan banata hai.
- Stack ka use karke postfix expression ko asaani se calculate kar sakte hain.
Suggested Diagram
Infix Expression: (A + B) * C
β Conversion
Postfix Expression: A B + C *
β Evaluation (using stack)
π Topic: Parse Trees and Syntax Trees
What is a Parse Tree?
English: A Parse Tree (or derivation tree) is a tree that shows the syntactic structure of a string according to a grammar. It represents how the start symbol of a grammar derives the string step by step.
Hinglish: Parse Tree ek tree hota hai jo dikhata hai ki ek string grammar ke rules ke hisaab se kaise ban rahi hai. Yeh grammar ke start symbol se string tak ke steps dikhata hai.
What is a Syntax Tree?
English: A Syntax Tree (or Abstract Syntax Tree, AST) is a simplified version of the parse tree. It focuses only on the essential parts of the syntax, ignoring unnecessary grammar details like parentheses.
Hinglish: Syntax Tree ek simplified parse tree hota hai jisme sirf important parts hote hain, aur jo extra grammar symbols hote hain (jaise parentheses) unhe hata diya jata hai.
5 Important Points about Parse Trees
- π‘ Shows complete derivation according to grammar.
- π‘ Includes all terminals and non-terminals.
- π‘ Root node is the start symbol of the grammar.
- π‘ Leaves represent terminals (actual tokens).
- π‘ Helps in verifying syntax correctness.
5 Important Points about Syntax Trees
- π‘ Focuses on semantic structure, not full grammar details.
- π‘ Leaves are operands (like variables or constants).
- π‘ Internal nodes are operators or constructs.
- π‘ Smaller and easier to use for further processing (like code generation).
- π‘ Removes redundant nodes (like parentheses or intermediate non-terminals).
Example: Parse Tree vs. Syntax Tree for an Expression
Expression: (a + b) * c
Parse Tree: Will show every grammar rule and parentheses as nodes.
Syntax Tree: Will show *
as root, with +
and c
as children, and a
, b
as leaves under +
.
Difference Between Parse Tree and Syntax Tree
Feature | Parse Tree | Syntax Tree (AST) |
---|---|---|
Detail Level | Very detailed, includes all grammar symbols | Simplified, only essential parts |
Purpose | Shows full grammar derivation | Shows semantic structure of code |
Size | Larger, can be complex | Smaller, concise |
Includes Parentheses | Yes | No |
Usage | Mainly for parsing and syntax checking | Used for semantic analysis, code gen |
Summary in Hinglish
- Parse Tree pura grammar ka structure dikhata hai, saare symbols ke sath.
- Syntax Tree sirf zaroori cheezein rakhta hai, simple aur chhota hota hai.
- Syntax Tree ko compiler aage code generation ke liye use karta hai.
- Parse Tree se hum confirm karte hain ki input grammar ke rules ko follow karta hai.
Suggested Diagram
Parse Tree: (Detailed with all grammar symbols)
E
/|\
( E + T )
/ \
a b
Syntax Tree: (Simplified)
*
/ \
+ c
/ \
a b
π Topic: Three Address Code (TAC)
Definition of Three Address Code
English: Three Address Code is an intermediate code representation used in compilers where each instruction contains at most three addresses (operands). It usually consists of a single operation and its operands, making it easy to translate and optimize.
Hinglish: Three Address Code ek intermediate code hai jisme har instruction mein 3 addresses ya operands tak hote hain. Yeh code simple instructions mein hota hai, jise machine code mein badalna aur optimize karna aasan hota hai.
5 Important Points about Three Address Code
- π‘ Each statement has one operator and up to two operands plus a result.
- π‘ Operands can be variables, constants, or temporary variables.
- π‘ Easy to generate from expressions and simple to optimize.
- π‘ Helps separate compiler phases (front-end and back-end).
- π‘ Commonly used in the form:
x = y op z
orx = op y
orgoto label
.
Formats of Three Address Code
- Assignment:
x = y
- Binary operation:
x = y + z
- Unary operation:
x = -y
- Copy:
x = y
- Goto statement:
goto L
- Conditional jump:
if x < y goto L
- Parameter passing:
param x
- Function call:
call p, n
(p
is procedure,n
is number of arguments) - Return statement:
return x
Example: TAC for an Expression
Expression: a = b + c * d
Three Address Code:
t1 = c * d
t2 = b + t1
a = t2
Explanation:
- First multiply
c
andd
, store in temporary variablet1
. - Then add
b
andt1
, store int2
. - Finally assign
t2
toa
.
Advantages of Three Address Code
- π Simple to generate and understand.
- π Easy to optimize and translate to machine code.
- π Facilitates code analysis and transformations.
- π Modular and portable intermediate representation.
- π Makes complex expressions easier to break down.
Disadvantages of Three Address Code
- π Can produce many temporary variables, increasing memory use.
- π More instructions compared to high-level code.
- π May require extra steps for optimization to reduce temporaries.
Summary in Hinglish
- Three Address Code mein instructions teen operands tak hote hain.
- Yeh intermediate code hai jo compiler ko source code se machine code mein badalne mein madad karta hai.
- Isme temporary variables use karke complex expressions ko chhote steps mein todte hain.
- Code optimize karna aur translate karna easy hota hai.
Suggested Diagram / Flow
Expression: a = b + c * d
c d
\ /
multiply (t1 = c * d)
|
b t1
\ /
add (t2 = b + t1)
|
a = t2
π Topic: Quadruples and Triples in Intermediate Code
What are Quadruples?
English: Quadruples are a way to represent intermediate code in compilers. Each instruction is stored as a record with four fields:
- Operator
- Argument 1
- Argument 2
- Result (where to store the output)
Hinglish: Quadruples ek tarah ka intermediate code representation hai jisme har instruction 4 parts mein hota hai: operator, do arguments, aur result jahan output store karna hai.
Example of Quadruple
Expression: a = b + c * d
Quadruple representation:
Operator | Arg1 | Arg2 | Result |
---|---|---|---|
* | c | d | t1 |
+ | b | t1 | t2 |
= | t2 | a |
What are Triples?
English: Triples are similar to quadruples but do not explicitly store the result field. Instead, the result is identified by the position (index) of the instruction in the list.
Hinglish: Triples bhi intermediate code ka ek form hai, lekin isme result field nahi hota. Result ko instruction ke number (position) se represent karte hain.
Example of Triples
Expression: a = b + c * d
Triple representation (index numbers added):
Index | Operator | Arg1 | Arg2 |
---|---|---|---|
0 | * | c | d |
1 | + | b | (0) |
2 | = | (1) |
Note: (0)
means the result of instruction 0, (1)
means result of instruction 1.
Comparison between Quadruples and Triples
Feature | Quadruples | Triples |
---|---|---|
Number of fields | 4 (Operator, Arg1, Arg2, Result) | 3 (Operator, Arg1, Arg2) |
Result storage | Explicitly stored in the Result field | Result identified by instruction index |
Easier to access | Yes, because result is named | Requires extra steps to find result |
Code size | Slightly larger due to result field | Smaller, no result field |
Flexibility | Easier for optimization and modification | Slightly more complex for modifications |
Advantages
- Quadruples:
- π Easy to understand and manipulate.
- π Result is explicitly available.
- π Good for code generation and optimization.
- Triples:
- π Requires less memory (no result field).
- π Compact representation.
Disadvantages
- Quadruples:
- π Uses more space due to result field.
- Triples:
- π More complex to handle result references during optimization.
- π Modifying code is harder because results are positional.
Summary in Hinglish
- Quadruples mein har instruction ke 4 parts hote hain, jisme result bhi clearly hota hai.
- Triples mein result ka field nahi hota, result ko instruction number se refer karte hain.
- Quadruples zyada flexible aur asaani se modify kar sakte hain, par space zyada leta hai.
- Triples space bachate hain, par thoda handling complex hota hai.
Suggested Diagram
Expression: a = b + c * d
Quadruples:
[ *, c, d, t1 ]
[ +, b, t1, t2 ]
[ =, t2, -, a ]
Triples:
0: [ *, c, d ]
1: [ +, b, (0) ]
2: [ =, (1), - ]
π Topic: Translation of Simple Statements and Control Flow Statements
What is Translation in Compiler?
English: Translation is the process of converting high-level language statements into intermediate code or machine code so the computer can understand and execute them.
Hinglish: Translation matlab source code ko aise code mein badalna jo machine samajh sake, jaise intermediate code ya machine code.
Translation of Simple Statements
English: Simple statements include assignments like x = y + z
, a = b
, etc. These statements are translated into intermediate code, often using three-address code.
Hinglish: Simple statements jaise x = y + z
ya a = b
ko intermediate code (jaise three address code) mein convert karte hain.
Example: Simple Statement Translation
Statement: a = b + c * d
Three Address Code:
t1 = c * d
t2 = b + t1
a = t2
Explanation:
- Pehle
c
aurd
ko multiply karo aur temporary variablet1
mein store karo. - Phir
b
aurt1
ko add karo aurt2
mein rakho. - Finally
t2
koa
mein assign karo.
Translation of Control Flow Statements
English: Control flow statements control the execution flow, like if
, while
, for
, goto
. They are translated into intermediate code using conditional and unconditional jumps (goto
).
Hinglish: Control flow statements, jaise if
, while
, for
, ko translation mein jump instructions use karte hain jisse program ka flow control hota hai.
Example: if statement Translation
Source code:
if (a < b)
c = a;
else
c = b;
Intermediate code (using labels and goto):
if a < b goto L1
goto L2
L1: c = a
goto L3
L2: c = b
L3:
Explanation:
- Agar
a < b
hai toh jump karo labelL1
par (line jahanc = a
hai). - Agar nahi, toh direct jump
L2
par (c = b
). - Phir dono ke baad jump
L3
par jahan se aage code continue hota hai.
Example: while loop Translation
Source code:
while (a < b) {
a = a + 1;
}
Intermediate code:
L1: if a >= b goto L2
a = a + 1
goto L1
L2:
Explanation:
- Label
L1
is the start of loop. - Check condition
a < b
, agar false ho toh jumpL2
(loop end). - Agar true hai toh
a = a + 1
karo, phir dobara start par jump karo (L1
).
Important Points about Control Flow Translation
- π‘ Labels are used to mark places in code to jump to.
- π‘
goto
is used for unconditional jump. - π‘ Conditional jump uses
if
statements to decide the flow. - π‘ Translation breaks complex control flow into simple jump instructions.
- π‘ Helps compiler manage program flow in machine or intermediate code.
Summary in Hinglish
- Simple statements jaise assignment ko temporary variables ke sath tod kar translate karte hain.
- Control flow jaise
if
,while
ko labels aur jump instructions ke through translate karte hain. - Labels aur
goto
se program ka flow control hota hai. - Yeh intermediate code machine ke liye asaani se samajhna possible banata hai.
Suggested Diagram
if (a < b) {
c = a;
} else {
c = b;
}
Translation:
if a < b goto L1
goto L2
L1: c = a
goto L3
L2: c = b
L3:
π Topic: Type Checking
What is Type Checking?
English: Type checking is the process in a compiler where it verifies that the data types of variables and expressions are used correctly according to the rules of the programming language.
Hinglish: Type checking matlab compiler ye check karta hai ki variables aur expressions ka data type sahi hai ya nahi, jaise number ko number se hi add karna, string ko string se hi jodna.
Why Type Checking is Important?
- π‘ Prevents errors like adding number to string.
- π‘ Ensures program behaves correctly.
- π‘ Helps catch bugs during compilation, not at runtime.
- π‘ Improves program reliability and safety.
- π‘ Helps the compiler generate correct code.
Examples of Type Checking
Expression | Result | Is it valid? |
---|---|---|
5 + 3 | Integer addition | Yes |
"hello" + "world" | String concatenation | Yes |
5 + "world" | Adding int and string | No (Type error) |
true && false | Boolean AND | Yes |
5 && true | Int and boolean AND | No (Type error) |
Types of Type Checking
- 1. Static Type Checking
- Done at compile time.
- Detects errors before running the program.
- Languages: C, Java, C++.
- 2. Dynamic Type Checking
- Done at runtime (while program is running).
- Errors detected when that line executes.
- Languages: Python, JavaScript.
Type Checking Techniques
- Type Inference: Compiler automatically figures out the type (like in modern languages).
- Type Conversion: Compiler changes one type to another if needed (like int to float).
- Type Compatibility: Checks if types can be combined or assigned.
Key Points about Type Checking
- π‘ Type checking ensures expressions and assignments are type-safe.
- π‘ Helps prevent crashes and unexpected behavior.
- π‘ Static checking is faster but less flexible.
- π‘ Dynamic checking is flexible but can cause runtime errors.
Summary in Hinglish
- Type checking compiler ka process hai jisme check karte hain ki variable ka data type sahi hai ya nahi.
- Static type checking compile time mein hota hai aur errors ko pehle hi pakad leta hai.
- Dynamic type checking runtime mein hota hai aur errors tab pakadta hai jab wo code chalta hai.
- Yeh programming errors ko kam karta hai aur program ko safe banata hai.
π Topic: Type Conversions
What is Type Conversion?
English: Type conversion is the process of converting a value from one data type to another so that operations between different types can be performed correctly.
Hinglish: Type conversion matlab ek data type ko dusre data type mein badalna, taaki different types ke beech operations sahi tareeke se ho sake.
Why Type Conversion is Needed?
- π‘ To perform operations between different types (like
int + float
). - π‘ To avoid type errors during compilation or execution.
- π‘ To allow mixed-type expressions in programming.
- π‘ To ensure correct storage and representation of data.
- π‘ To follow language or system rules about type usage.
Types of Type Conversions
- 1. Implicit Type Conversion (Type Coercion)
- Automatically done by the compiler or interpreter.
- Programmer doesnβt need to write conversion code.
- Example: Adding
int
andfloat
βint
is automatically converted tofloat
.
- 2. Explicit Type Conversion (Type Casting)
- Programmer manually converts one type to another.
- Done using casting operators or functions.
- Example:
(float) 5
converts integer5
to float5.0
.
Examples of Type Conversions
Implicit conversion:
int a = 5;
float b = 3.2;
float c = a + b; // a is converted to float automatically
Explicit conversion:
float x = 7.8;
int y = (int) x; // x is explicitly converted to int (7)
Common Conversions
int
βfloat
float
βint
(may lose decimal part)char
βint
(ASCII value)int
βchar
(character representation)string
βint/float
(using functions likeatoi
orstof
)
Important Points about Type Conversions
- π‘ Implicit conversion is safe but can sometimes cause unexpected results.
- π‘ Explicit conversion gives programmer control but may cause data loss.
- π‘ Some conversions are not allowed or need special handling (like converting string to int).
- π‘ Conversions affect how data is stored and used in memory.
Summary in Hinglish
- Type conversion ek process hai jisme ek data type ko doosre mein badalte hain.
- Implicit conversion automatically hota hai compiler ke dwara.
- Explicit conversion programmer khud karta hai casting ke through.
- Kabhi-kabhi conversion mein data loss bhi ho sakta hai, jaise
float
koint
mein convert karne par decimal hat jaata hai.
π Topic: Equivalence of Type Expressions
What is Equivalence of Type Expressions?
English: Equivalence of type expressions means checking whether two type expressions describe the same type. This is important for type checking and ensuring operations are done on compatible types.
Hinglish: Equivalence of type expressions matlab do alag type expressions ko compare karna ki kya wo same type ko represent karte hain ya nahi.
Why is it Important?
- π‘ To verify if two variables or expressions have compatible types.
- π‘ Helps compiler decide if operations or assignments are valid.
- π‘ Ensures safety and correctness of programs.
- π‘ Avoids errors when types look different but actually mean the same.
Example of Type Equivalence
Suppose we have two types: int
and integer
.
If in a language both represent the same data type, then these type expressions are equivalent.
For structured types:
Type1 = struct { int x; float y; }
Type2 = struct { int x; float y; }
Type1
and Type2
are equivalent if the fields have same types and order.
Types of Equivalence
- 1. Name Equivalence
- Two types are equivalent if they have the same name.
- Even if structure is same, different names mean not equivalent.
- Example:
type A = struct { int x; } type B = struct { int x; }
A
andB
are NOT equivalent by name equivalence.
- 2. Structural Equivalence
- Two types are equivalent if their structure is identical.
- Names donβt matter, only the content and layout matter.
- Example:
struct { int x; int y; } struct { int x; int y; }
Equivalent by structure even if unnamed.
Important Points about Equivalence
- π‘ Name equivalence is simple but restrictive.
- π‘ Structural equivalence is flexible but can be complex to check.
- π‘ Some languages prefer one type equivalence method over another.
- π‘ Equivalence is crucial during assignments, parameter passing, and type checking.
Summary in Hinglish
- Type expressions ki equivalence check karte hain ki do types same hain ya nahi.
- Name equivalence mein sirf naam count karta hai.
- Structural equivalence mein structure (fields, order) check karte hain.
- Yeh check karna compiler ke liye important hota hai taaki sahi program likha ja sake.
π Topic: Overloading of Functions and Operations
What is Overloading?
English: Overloading means having more than one function or operator with the same name but different parameters or types, so they perform different tasks depending on the input.
Hinglish: Overloading matlab ek hi naam ke function ya operation ka use alag-alag tareeke se karna, jaise alag input ke liye alag kaam karna.
Why is Overloading Used?
- π‘ To make code simpler and readable.
- π‘ Same name can be used for similar operations on different data types.
- π‘ Helps in creating flexible and reusable code.
- π‘ Avoids confusion by keeping consistent names.
- π‘ Allows different behavior with same function/operator name.
Types of Overloading
- 1. Function Overloading
- Multiple functions with the same name but different parameters (number or type).
- Compiler decides which function to call based on arguments.
- Example:
int add(int a, int b) { return a + b; } float add(float a, float b) { return a + b; }
- 2. Operator Overloading
- Giving new meaning to operators like
+
,-
,*
, etc. for user-defined types (like classes). - Example: For a class Complex, overloading
+
to add two complex numbers.
- Giving new meaning to operators like
Examples of Overloading in Action
Function Overloading:
void print(int x) { cout << x; }
void print(string s) { cout << s; }
print(5); // calls print(int)
print("Hi"); // calls print(string)
Operator Overloading:
class Complex {
float real, imag;
public:
Complex operator+(const Complex& c) {
return Complex(real + c.real, imag + c.imag);
}
};
Important Points about Overloading
- π‘ Overloading increases program readability.
- π‘ Overloaded functions must differ in parameter list.
- π‘ Return type alone is not enough for overloading.
- π‘ Operator overloading allows customizing operations for objects.
- π‘ Not all operators can be overloaded (e.g.,
.
operator in C++).
Summary in Hinglish
- Overloading ka matlab hai ek naam ke functions ya operators ko alag-alag tareeke se use karna.
- Function overloading mein same naam ke functions alag parameters ke saath hote hain.
- Operator overloading mein hum operators ka meaning change kar sakte hain user-defined types ke liye.
- Isse code clean, readable aur flexible hota hai.