Programming Languages (Concepts)Programming Languages (Concepts)
How languages are built, how they bind names, pass parameters and manage memory — plus quick "what is the output?" tricks in Python, Java and C.Language কীভাবে তৈরি হয়, কীভাবে name bind করে, parameter pass করে আর memory manage করে — সাথে Python, Java আর C-এর ছোট ছোট "output কী হবে?" trick।
- Language Paradigms and HistoryLanguage Paradigms আর History
- Implementation Methods (Compile, Interpret, Hybrid)Implementation Methods (Compile, Interpret, Hybrid)
- Names, Binding, Scope and LifetimeNames, Binding, Scope আর Lifetime
- Data Types and Type SystemsData Types আর Type Systems
- Expressions and Control StructuresExpressions আর Control Structures
- Subprograms and Parameter PassingSubprograms আর Parameter Passing
- Memory Management and ExceptionsMemory Management আর Exceptions
- Multi-language MCQ CornerMulti-language MCQ Corner
- Practice Questions (IICT Style)Practice Questions (IICT Style)
1. Language Paradigms and History1. Language Paradigms আর History
A paradigm is a style of thinking about a program. It tells you how you describe the work to the computer. Some languages follow one paradigm. Many modern languages (Python, C++, JavaScript) mix several.
The five main paradigms
- Imperative / Procedural — You give step-by-step commands. You change variables (state) with assignment. Code is grouped into procedures (functions). Examples: C, Fortran, COBOL, Pascal.
- Object-Oriented (OOP) — You group data and the functions that work on it into objects. Key ideas: encapsulation, inheritance, polymorphism. Examples: Java, C++, C#, Smalltalk. (Full detail in Chapter 02.)
- Functional — A program is a set of mathematical functions. You avoid changing state. You use recursion instead of loops. Functions can be passed like values (first-class functions). Examples: Lisp, Haskell, ML, Scheme, F#.
- Logic (Declarative) — You write facts and rules. Then you ask a question (query). The system finds the answer by itself using logical inference. Example: Prolog.
- Scripting — Small, quick programs, usually interpreted, dynamically typed, used to glue tools together or automate tasks. Examples: Python, Perl, JavaScript, Bash, PHP, Ruby.
There is one more big word you should know: declarative. In a declarative language you say what you want, not how to get it. Functional and logic languages are declarative. SQL is also declarative: you write SELECT name FROM student WHERE cgpa > 3.5, and the database decides how to find it.
Paradigm মানে program নিয়ে চিন্তা করার একটা style। এটা বলে দেয় computer-কে কাজটা তুমি কীভাবে বুঝিয়ে বলবে। কিছু language একটা paradigm মেনে চলে। আজকের অনেক language (Python, C++, JavaScript) কয়েকটা paradigm মিশিয়ে ব্যবহার করে।
মূল পাঁচটা paradigm
- Imperative / Procedural — ধাপে ধাপে command দাও। Assignment দিয়ে variable (state) বদলাও। Code-গুলো procedure (function)-এ ভাগ করা থাকে। উদাহরণ: C, Fortran, COBOL, Pascal।
- Object-Oriented (OOP) — Data আর সেই data-র ওপর কাজ করা function-গুলোকে একসাথে object-এ রাখো। মূল idea: encapsulation, inheritance, polymorphism। উদাহরণ: Java, C++, C#, Smalltalk। (বিস্তারিত Chapter 02-এ।)
- Functional — Program হলো কিছু mathematical function-এর সেট। State বদলানো এড়িয়ে চলা হয়। Loop-এর বদলে recursion ব্যবহার হয়। Function-কে value-এর মতো pass করা যায় (first-class function)। উদাহরণ: Lisp, Haskell, ML, Scheme, F#।
- Logic (Declarative) — তুমি fact আর rule লেখো। তারপর একটা প্রশ্ন (query) করো। System নিজেই logical inference দিয়ে উত্তর খুঁজে বের করে। উদাহরণ: Prolog।
- Scripting — ছোট, দ্রুত লেখা program, সাধারণত interpreted আর dynamically typed; tool জোড়া লাগাতে বা কাজ automate করতে লাগে। উদাহরণ: Python, Perl, JavaScript, Bash, PHP, Ruby।
আরেকটা বড় শব্দ জানা দরকার: declarative। Declarative language-এ তুমি বলো কী চাও, কীভাবে পাবে সেটা না। Functional আর logic language declarative। SQL-ও declarative: তুমি লেখো SELECT name FROM student WHERE cgpa > 3.5, আর database নিজে ঠিক করে কীভাবে খুঁজবে।
/* Imperative (C): change a variable step by step */
int sum = 0;
for (int i = 1; i <= n; i++) sum = sum + i;
// Object-oriented (Java): behaviour lives inside a class
class Summer { int sumTo(int n) { int s = 0; for (int i = 1; i <= n; i++) s += i; return s; } }
;; Functional (Scheme/Lisp): no loop, no assignment, only recursion
(define (sum n) (if (= n 0) 0 (+ n (sum (- n 1)))))
% Logic (Prolog): state facts and rules, then ask a query
sum(0, 0).
sum(N, S) :- N > 0, N1 is N - 1, sum(N1, S1), S is S1 + N.
?- sum(4, S). % Prolog answers: S = 10
A short Prolog example (logic paradigm)ছোট একটা Prolog example (logic paradigm)
parent(karim, rahim). % fact: karim is parent of rahim
parent(rahim, sumi). % fact: rahim is parent of sumi
grandparent(X, Z) :- parent(X, Y), parent(Y, Z). % rule
?- grandparent(karim, Who).
Who = sumi.
We never wrote a loop or a search. Prolog found Who = sumi by itself using unification and backtracking. That is the heart of logic programming.
আমরা কোনো loop বা search লিখিনি। Prolog নিজেই unification আর backtracking দিয়ে Who = sumi বের করেছে। এটাই logic programming-এর মূল কথা।
Timeline of important languagesগুরুত্বপূর্ণ language-গুলোর timeline
| Year | Language | CreatorCreator | Why it mattersকেন গুরুত্বপূর্ণ |
|---|---|---|---|
| 1957 | Fortran | John Backus (IBM) | First widely used high-level language. Made for science and number crunching.প্রথম বহুল ব্যবহৃত high-level language। Science আর হিসাব-নিকাশের জন্য। |
| 1958 | Lisp | John McCarthy | First functional language. Used in AI. Gave us garbage collection and recursion-heavy style.প্রথম functional language। AI-তে ব্যবহার হতো। Garbage collection আর recursion-ভিত্তিক style এখান থেকেই। |
| 1959 | COBOL | Committee (Grace Hopper's ideas)Committee (Grace Hopper-এর idea) | Business data processing. English-like syntax. Still runs in banks.Business data processing। English-এর মতো syntax। এখনো bank-এ চলে। |
| 1960 | ALGOL 60 | CommitteeCommittee | Introduced block structure and BNF grammar. Parent of Pascal and C.Block structure আর BNF grammar আনে। Pascal আর C-এর পূর্বপুরুষ। |
| 1972 | C | Dennis Ritchie (Bell Labs) | Systems programming. Used to write UNIX. Fast and close to hardware.Systems programming। UNIX লিখতে ব্যবহার হয়। দ্রুত আর hardware-এর কাছাকাছি। |
| 1972 | Prolog | Alain Colmerauer | Logic programming. Used in AI and expert systems.Logic programming। AI আর expert system-এ ব্যবহার হয়। |
| 1983/85 | C++ | Bjarne Stroustrup | "C with classes". Added OOP to C."C with classes"। C-তে OOP যোগ করে। |
| 1991 | Python | Guido van Rossum | Easy to read, dynamically typed scripting language. Huge in AI/data today.পড়তে সহজ, dynamically typed scripting language। আজ AI/data-তে সবচেয়ে জনপ্রিয়। |
| 1995 | Java | James Gosling (Sun) | "Write once, run anywhere" using bytecode + JVM. Pure OOP style.Bytecode + JVM দিয়ে "Write once, run anywhere"। OOP style। |
| 1995 | JavaScript | Brendan Eich | Language of the web browser.Web browser-এর language। |
Generations of languages (1GL to 5GL)Language-এর generation (1GL থেকে 5GL)
| Generation | What it isএটা কী | ExampleExample |
|---|---|---|
| 1GL | Machine language. Pure 0s and 1s. CPU runs it directly. Machine dependent.Machine language। শুধু 0 আর 1। CPU সরাসরি চালায়। Machine dependent। | 10110000 01100001 |
| 2GL | Assembly language. Short words (mnemonics) for machine instructions. Needs an assembler.Assembly language। Machine instruction-এর ছোট নাম (mnemonic)। Assembler লাগে। | MOV AL, 61h |
| 3GL | High-level, procedural or OOP languages. Machine independent. Needs a compiler or interpreter.High-level, procedural বা OOP language। Machine independent। Compiler বা interpreter লাগে। | C, C++, Java, Fortran, Python |
| 4GL | Very high-level, often non-procedural. Close to human language. Used for databases and reports.অনেক high-level, প্রায়ই non-procedural। মানুষের ভাষার কাছাকাছি। Database আর report-এর জন্য। | SQL, MATLAB, report generators |
| 5GL | Solve problems using constraints and logic given by the programmer. Used in AI.Programmer-এর দেওয়া constraint আর logic দিয়ে problem solve করে। AI-তে ব্যবহার হয়। | Prolog, Mercury, OPS5 |
Language evaluation criteriaLanguage evaluation criteria
How do we judge if a language is "good"? The classic textbook (Sebesta) uses four criteria:
- Readability — How easy is it to read and understand the code? Helped by simplicity, few ways to do one thing, clear syntax, good data types. Hurt by feature multiplicity (e.g.
x++,++x,x += 1,x = x + 1all do the same) and operator overloading used badly. - Writability — How easy is it to write a program for a task? Helped by abstraction (functions, classes) and expressivity (powerful short operators like
count++). - Reliability — Does the program do what it should in all conditions? Helped by type checking, exception handling, and avoiding aliasing (two names for one memory cell).
- Cost — Total cost: training programmers, writing code, compiling, running, the compiler/tools price, poor reliability, and maintenance (often the biggest cost).
Other criteria sometimes asked: portability (run on many machines), generality (useful for many kinds of tasks), well-definedness (clear official definition).
একটা language "ভালো" কিনা কীভাবে বিচার করব? Classic textbook (Sebesta) চারটা criterion ব্যবহার করে:
- Readability — Code পড়া আর বোঝা কত সহজ? Simplicity, এক কাজ করার কম উপায়, পরিষ্কার syntax, ভালো data type থাকলে বাড়ে। কমে যায় feature multiplicity-তে (যেমন
x++,++x,x += 1,x = x + 1সব একই কাজ করে) আর ভুলভাবে ব্যবহার করা operator overloading-এ। - Writability — কোনো কাজের জন্য program লেখা কত সহজ? Abstraction (function, class) আর expressivity (ছোট কিন্তু শক্তিশালী operator, যেমন
count++) এটা বাড়ায়। - Reliability — সব অবস্থায় program ঠিক কাজ করে কি না? Type checking, exception handling আর aliasing (এক memory cell-এর দুই নাম) এড়ানো এটা বাড়ায়।
- Cost — মোট খরচ: programmer training, code লেখা, compile করা, চালানো, compiler/tool-এর দাম, কম reliability-র ক্ষতি, আর maintenance (প্রায়ই সবচেয়ে বড় খরচ)।
মাঝে মাঝে আরও কিছু criterion আসে: portability (অনেক machine-এ চলে), generality (অনেক ধরনের কাজে লাগে), well-definedness (পরিষ্কার official definition)।
2. Implementation Methods (Compile, Interpret, Hybrid)2. Implementation Methods (Compile, Interpret, Hybrid)
The CPU only understands machine code. So a program written in a high-level language must be translated or run by another program. There are three main ways.
1) Pure compilation
A compiler translates the whole source program into machine code once, before running. The output (an executable file) then runs directly on the CPU. Examples: C, C++, Fortran, Go, Rust.
- Very fast execution, because translation is already done.
- Errors are reported before the program runs (compile-time errors).
- The executable is tied to one machine/OS (less portable).
2) Pure interpretation
An interpreter reads the source program and runs it statement by statement. No separate machine-code file is made. Examples: early BASIC, shell scripts (Bash), classic JavaScript engines.
- Slow execution — often 10 to 100 times slower than compiled code, because every statement is decoded every time it runs (even inside a loop).
- Easy debugging — error messages point to the exact source line, and you can run code interactively.
- Needs more memory space (the source and symbol table stay in memory).
3) Hybrid implementation
A hybrid system first compiles the source into an intermediate code (called bytecode), then an interpreter (a virtual machine) runs that bytecode. Examples: Java (.java → javac → .class bytecode → JVM), Python (.py → .pyc bytecode → Python VM), C# (→ CIL → .NET CLR).
Bytecode is not tied to any real CPU. So the same .class file runs on Windows, Linux, or Mac as long as a JVM exists. That is Java's famous "Write Once, Run Anywhere".
JIT (Just-In-Time) compilation
A JIT compiler sits inside the virtual machine. While the program runs, it finds "hot" code (methods or loops that run many times) and compiles that bytecode into real machine code. Next time, the fast machine code runs directly. Modern JVMs (HotSpot), .NET, and JavaScript V8 all use JIT. This is why Java today is almost as fast as C for many tasks.
CPU শুধু machine code বোঝে। তাই high-level language-এ লেখা program-কে হয় translate করতে হয়, নয়তো অন্য একটা program দিয়ে চালাতে হয়। তিনটা মূল উপায় আছে।
১) Pure compilation
Compiler চালানোর আগেই পুরো source program-কে একবারে machine code-এ translate করে। Output (একটা executable file) তারপর সরাসরি CPU-তে চলে। উদাহরণ: C, C++, Fortran, Go, Rust।
- Execution খুব দ্রুত, কারণ translation আগেই হয়ে গেছে।
- Program চালানোর আগেই error জানা যায় (compile-time error)।
- Executable একটা নির্দিষ্ট machine/OS-এর সাথে বাঁধা (কম portable)।
২) Pure interpretation
Interpreter source program পড়ে আর একটা একটা statement করে চালায়। আলাদা কোনো machine-code file তৈরি হয় না। উদাহরণ: পুরোনো BASIC, shell script (Bash), পুরোনো JavaScript engine।
- Execution ধীর — প্রায়ই compiled code-এর চেয়ে 10 থেকে 100 গুণ ধীর, কারণ প্রতিটা statement যতবার চলে ততবার decode হয় (loop-এর ভেতরেও)।
- Debugging সহজ — error message ঠিক source line দেখায়, আর code interactively চালানো যায়।
- বেশি memory লাগে (source আর symbol table memory-তে থাকে)।
৩) Hybrid implementation
Hybrid system প্রথমে source-কে একটা intermediate code-এ (নাম bytecode) compile করে, তারপর একটা interpreter (virtual machine) সেই bytecode চালায়। উদাহরণ: Java (.java → javac → .class bytecode → JVM), Python (.py → .pyc bytecode → Python VM), C# (→ CIL → .NET CLR)।
Bytecode কোনো আসল CPU-এর সাথে বাঁধা না। তাই JVM থাকলে একই .class file Windows, Linux বা Mac — সবখানে চলে। এটাই Java-র বিখ্যাত "Write Once, Run Anywhere"।
JIT (Just-In-Time) compilation
JIT compiler virtual machine-এর ভেতরে থাকে। Program চলার সময় এটা "hot" code খুঁজে বের করে (যেসব method বা loop অনেকবার চলে) আর সেই bytecode-কে আসল machine code-এ compile করে ফেলে। পরেরবার দ্রুত machine code সরাসরি চলে। আধুনিক JVM (HotSpot), .NET আর JavaScript V8 সবাই JIT ব্যবহার করে। এজন্যই আজকের Java অনেক কাজে প্রায় C-এর মতো দ্রুত।
Comparison tableComparison table
| Pointবিষয় | Compiler | Interpreter | Hybrid (Bytecode + VM) |
|---|---|---|---|
| Translation unitTranslate-এর একক | Whole program at onceপুরো program একবারে | One statement at a timeএকবারে একটা statement | Whole program to bytecode, then VM runs itপুরো program bytecode-এ, তারপর VM চালায় |
| Execution speedExecution speed | Fastestসবচেয়ে দ্রুত | Slowestসবচেয়ে ধীর | Medium (fast with JIT)মাঝারি (JIT থাকলে দ্রুত) |
| Output fileOutput file | Machine code executableMachine code executable | Noneকিছু না | Bytecode (.class, .pyc)Bytecode (.class, .pyc) |
| Error reportingError reporting | All syntax errors after full scanপুরো scan-এর পরে সব syntax error | Stops at the first error lineপ্রথম error line-এ থেমে যায় | Compile errors first, then run-time errorsআগে compile error, পরে run-time error |
| PortabilityPortability | Low (recompile per platform)কম (প্রতি platform-এ আবার compile) | High (if interpreter exists)বেশি (interpreter থাকলে) | High (if VM exists)বেশি (VM থাকলে) |
| ExamplesExamples | C, C++, Fortran, Rust, Go | Bash, early BASIC, early JavaScript | Java, Python, C#, Kotlin |
Compiler phases — one-line recapCompiler phases — এক লাইনে recap
- Lexical analysis (scanner) — breaks characters into tokens (
int,x,=,5). - Syntax analysis (parser) — checks grammar, builds a parse tree.
- Semantic analysis — type checking, undeclared variables.
- Intermediate code generation — e.g. three-address code.
- Code optimization — make it faster/smaller.
- Code generation — produce target machine code.
The symbol table and error handler are used by all phases. Full detail with parsing examples is in Chapter 07, Lexical Analysis and Parsing.
- Lexical analysis (scanner) — character-গুলোকে token-এ ভাগ করে (
int,x,=,5)। - Syntax analysis (parser) — grammar check করে, parse tree বানায়।
- Semantic analysis — type checking, undeclared variable ধরা।
- Intermediate code generation — যেমন three-address code।
- Code optimization — code-কে দ্রুত/ছোট করা।
- Code generation — target machine code তৈরি।
Symbol table আর error handler সব phase-এ ব্যবহার হয়। Parsing example সহ বিস্তারিত আছে Chapter 07, Lexical Analysis and Parsing-এ।
Preprocessor, assembler, linker and loaderPreprocessor, assembler, linker আর loader
- Preprocessor (C/C++) — runs before the compiler. Handles
#include,#definemacros,#ifdef. Pure text replacement. - Assembler — turns assembly code into object code (machine code with unresolved addresses).
- Linker — joins many object files and library code into one executable. It resolves external references (e.g. your call to
printfgets the real address ofprintf). - Loader — part of the OS. It copies the executable from disk into memory, fixes addresses (relocation) and starts it.
Full chain for C: prog.c → preprocessor → compiler → assembler → prog.o → linker → a.out → loader → running process.
- Preprocessor (C/C++) — compiler-এর আগে চলে।
#include,#definemacro,#ifdefhandle করে। শুধু text replacement। - Assembler — assembly code-কে object code-এ (address এখনো ঠিক না করা machine code) রূপান্তর করে।
- Linker — অনেকগুলো object file আর library code জোড়া দিয়ে একটা executable বানায়। এটা external reference resolve করে (যেমন তোমার
printfcall পায়printf-এর আসল address)। - Loader — OS-এর অংশ। Executable-কে disk থেকে memory-তে copy করে, address ঠিক করে (relocation) আর চালু করে।
C-এর পুরো chain: prog.c → preprocessor → compiler → assembler → prog.o → linker → a.out → loader → running process।
Static vs dynamic linkingStatic vs dynamic linking
| Pointবিষয় | Static linking | Dynamic linking |
|---|---|---|
| When library code is addedLibrary code কখন যোগ হয় | At link time — copied into the executableLink time-এ — executable-এর ভেতরে copy হয় | At load time or run time — only a reference is keptLoad time বা run time-এ — শুধু একটা reference থাকে |
| Library fileLibrary file | .a (Linux), .lib (Windows) | .so (Linux), .dll (Windows) |
| Executable sizeExecutable size | Largeবড় | Smallছোট |
| Memory use (many programs)Memory ব্যবহার (অনেক program) | Each program has its own copyপ্রতিটা program-এর আলাদা copy | One shared copy in memoryMemory-তে একটাই shared copy |
| Library updateLibrary update | Must re-link the programProgram আবার link করতে হয় | Just replace the .so/.dll fileশুধু .so/.dll file বদলালেই হয় |
| RiskRisk | None at run time; works aloneRun time-এ ঝুঁকি নেই; একাই চলে | "DLL hell" — missing or wrong version breaks the program"DLL hell" — file না থাকলে বা ভুল version হলে program ভাঙে |
3. Names, Binding, Scope and Lifetime3. Names, Binding, Scope আর Lifetime
A variable is more than a name. Sebesta describes it with six attributes: name, address, value, type, lifetime, scope. The address is also called the l-value (used on the left of =). The value is the r-value.
When two different names point to the same memory cell, they are called aliases. Aliasing (through pointers, references, or unions) hurts readability and reliability.
What is binding?
A binding is a link between two things — like a name and its type, or a variable and its memory cell. The binding time is when that link is made.
Variable শুধু একটা নাম না। Sebesta এটাকে ছয়টা attribute দিয়ে বর্ণনা করেন: name, address, value, type, lifetime, scope। Address-কে l-value-ও বলে (=-এর বামে ব্যবহার হয়)। Value হলো r-value।
দুটো আলাদা নাম যখন একই memory cell-কে point করে, তাদের বলে alias। Aliasing (pointer, reference বা union দিয়ে) readability আর reliability কমায়।
Binding কী?
Binding হলো দুটো জিনিসের মধ্যে সংযোগ — যেমন একটা name আর তার type, বা একটা variable আর তার memory cell। Binding time মানে সেই সংযোগ কখন হয়।
| Binding time | Example (C / Java)Example (C / Java) |
|---|---|
| Language design time | * is bound to the multiplication operation; int is a keyword.* multiplication operation-এর সাথে bound; int একটা keyword। |
| Language implementation time | The range of int in C (16 or 32 bits) is decided by the compiler writer.C-তে int-এর range (16 বা 32 bit) compiler writer ঠিক করেন। |
| Compile time | A C/Java variable is bound to its type: int count;C/Java-তে variable-এর type bind হয়: int count; |
| Link time | A call to a library function is bound to that function's code.Library function-এর call সেই function-এর code-এর সাথে bind হয়। |
| Load time | A C static or global variable is bound to a memory cell.C-এর static বা global variable একটা memory cell-এর সাথে bind হয়। |
| Run time | A local (non-static) variable gets a stack cell when the function is called. A value is bound to a variable by assignment. A Python variable gets its type.Function call হলে local (non-static) variable stack cell পায়। Assignment-এ variable-এর সাথে value bind হয়। Python variable-এর type bind হয়। |
A binding is static if it happens before run time and never changes while the program runs. It is dynamic if it happens during run time or can change.
Static vs dynamic type binding
- Static type binding: the type is fixed before running, by an explicit declaration (
int x;in C) or by type inference (var x = 5;in Java/C#,auto x = 5;in C++, ML/Haskell). The type ofxcan never change later. - Dynamic type binding: the type is bound when a value is assigned, at run time. The same name can hold different types over time. Python, JavaScript, PHP, Ruby.
Binding যদি run time-এর আগে হয় আর program চলার সময় আর না বদলায়, তাহলে সেটা static। আর যদি run time-এর মধ্যে হয় বা বদলাতে পারে, তাহলে dynamic।
Static vs dynamic type binding
- Static type binding: চালানোর আগেই type ঠিক হয়ে যায়, হয় explicit declaration দিয়ে (C-তে
int x;), নয়তো type inference দিয়ে (Java/C#-এvar x = 5;, C++-এauto x = 5;, ML/Haskell)। পরেx-এর type আর বদলানো যায় না। - Dynamic type binding: run time-এ value assign করার সময় type bind হয়। একই নাম সময়ের সাথে বিভিন্ন type রাখতে পারে। Python, JavaScript, PHP, Ruby।
# Python: dynamic type binding
x = 10 # x is bound to int
x = "BUET" # now x is bound to str — allowed
x = [1, 2, 3] # now a list
// Java: static type binding
int x = 10;
x = "BUET"; // compile-time ERROR: incompatible types
Dynamic typing is flexible, but a type error is found only when that line runs. It is also slower, because the type must be checked at run time.
Dynamic typing flexible, কিন্তু type error ধরা পড়ে শুধু যখন ওই line চলে। এটা ধীরও, কারণ run time-এ type check করতে হয়।
Lifetime: four categories of variablesLifetime: variable-এর চারটা category
The lifetime of a variable is the time during which it is bound to a memory cell. It starts at allocation and ends at deallocation.
Variable-এর lifetime মানে যতক্ষণ এটা একটা memory cell-এর সাথে bound থাকে। এটা শুরু হয় allocation-এ আর শেষ হয় deallocation-এ।
| Category | When storage is boundকখন storage bind হয় | ExampleExample | Plus / minusসুবিধা / অসুবিধা |
|---|---|---|---|
| Static | Before run (load time); lives for the whole programচালানোর আগে (load time); পুরো program জুড়ে থাকে | C global and static locals, Java static fieldsC global আর static local, Java static field | + fast, history-sensitive. − no recursion support+ দ্রুত, আগের value মনে রাখে। − recursion চলে না |
| Stack-dynamic | When its declaration runs (function call); freed on returnDeclaration চলার সময় (function call); return-এ free | Local variables in C, C++, Java methodsC, C++, Java method-এর local variable | + supports recursion, saves memory. − a bit slower, no history+ recursion চলে, memory বাঁচে। − একটু ধীর, আগের value থাকে না |
| Explicit heap-dynamic | When the programmer asks, using an operator/functionProgrammer যখন operator/function দিয়ে চায় | new / delete (C++), malloc / free (C), new (Java objects) | + dynamic structures (linked list, tree). − pointer errors, leaks+ dynamic structure (linked list, tree)। − pointer error, leak |
| Implicit heap-dynamic | Automatically, every time a value is assignedValue assign করলেই আপনা-আপনি | Python/JavaScript variables, JS arrays and stringsPython/JavaScript variable, JS array আর string | + very flexible. − slow, errors found late+ খুব flexible। − ধীর, error দেরিতে ধরা পড়ে |
/* C example: three lifetimes in one program */
#include <stdlib.h>
int total = 0; // static (global) — whole program
void f(void) {
static int calls = 0; // static — keeps value between calls
int temp = 5; // stack-dynamic — dies when f returns
int *p = malloc(sizeof(int)); // *p is explicit heap-dynamic
calls++;
free(p); // lifetime of *p ends here
}
Scope: static (lexical) vs dynamicScope: static (lexical) vs dynamic
The scope of a variable is the part of the program where the name can be seen. Lifetime is about time; scope is about text/place. They are different: a C static local lives for the whole program but can be seen only inside its function.
When a function uses a name that is not declared locally (a non-local reference), which declaration does it mean? Two rules:
- Static (lexical) scoping — look in the block/function where the code is written, then in the enclosing block in the source text (its static parent), and so on outward. Decided at compile time. Used by C, C++, Java, Python, JavaScript, Pascal, Ada, and almost all modern languages.
- Dynamic scoping — look in the function itself, then in the function that called it, then its caller, and so on back down the call chain at run time. Used by early Lisp, APL, SNOBOL, Perl (
local), and Bash (localvariables).
Variable-এর scope মানে program-এর যে অংশে নামটা দেখা যায়। Lifetime সময় নিয়ে; scope জায়গা/text নিয়ে। দুটো আলাদা: C-এর static local পুরো program জুড়ে বেঁচে থাকে, কিন্তু শুধু তার function-এর ভেতরেই দেখা যায়।
একটা function যখন এমন নাম ব্যবহার করে যেটা locally declare করা নেই (non-local reference), তখন সেটা কোন declaration বোঝায়? দুটো rule:
- Static (lexical) scoping — code যেখানে লেখা সেই block/function-এ খোঁজো, তারপর source text-এ তাকে ঘিরে থাকা block-এ (তার static parent), এভাবে বাইরের দিকে। Compile time-এ ঠিক হয়। C, C++, Java, Python, JavaScript, Pascal, Ada — প্রায় সব আধুনিক language এটা ব্যবহার করে।
- Dynamic scoping — function-এর নিজের ভেতরে খোঁজো, তারপর যে function তাকে call করেছে তার ভেতরে, তারপর তার caller-এ — run time-এর call chain ধরে পেছনের দিকে। পুরোনো Lisp, APL, SNOBOL, Perl (
local) আর Bash (localvariable) এটা ব্যবহার করে।
int n = 10; // global n
void show() { print(n); } // n is NOT local here
void change() { n = n + 5; } // n is NOT local here
void f() { int n = 1; // f has its OWN local n
change();
show(); }
main() { f();
show(); }
Static scoping trace — show and change are written at the top level. Their static parent is the global block. So their n always means the global n, no matter who calls them.
maincallsf.fmakes localn = 1(this one is never used by others).fcallschange: globaln = 10 + 5 = 15.fcallsshow: prints globaln→ 15.- Back in
main,showprints globaln→ 15.
Output (static): 15 15
Dynamic scoping trace — for a non-local n, look back through the callers. The most recent active n wins.
maincallsf.fmakes localn = 1. Call chain: main → f.fcallschange.changehas non. Its caller isf, which hasn. Sof'sn = 1 + 5 = 6. Globalnstays 10.fcallsshow. Callerfhasn = 6→ prints 6.freturns; itsnis gone.maincallsshow. Callermainhas non, so we reach the globaln = 10→ prints 10.
Output (dynamic): 6 10
(Verified: the C version prints 15 15. The same program in Bash with local n=1 — Bash is dynamically scoped — prints 6 10.)
Static scoping trace — show আর change top level-এ লেখা। তাদের static parent হলো global block। তাই যে-ই call করুক, তাদের n সবসময় global n।
mainf-কে call করে।flocaln = 1বানায় (এটা আর কেউ ব্যবহার করে না)।fchange-কে call করে: globaln = 10 + 5 = 15।fshow-কে call করে: globalnprint → 15।main-এ ফিরেshowglobalnprint করে → 15।
Output (static): 15 15
Dynamic scoping trace — non-local n-এর জন্য caller-দের মধ্যে পেছনে খোঁজো। সবচেয়ে সাম্প্রতিক active n-টাই নেওয়া হয়।
mainf-কে call করে।flocaln = 1বানায়। Call chain: main → f।fchange-কে call করে।change-এ কোনোnনেই। তার callerf-এnআছে। তাইf-এরn = 1 + 5 = 6। Globaln10-ই থাকে।fshow-কে call করে। Callerf-এn = 6→ print 6।freturn করে; তারnশেষ।mainshow-কে call করে। Callermain-এnনেই, তাই globaln = 10পাই → print 10।
Output (dynamic): 6 10
(Verified: C version print করে 15 15। একই program Bash-এ local n=1 দিয়ে লিখলে — Bash dynamically scoped — print করে 6 10।)
n means just by reading show.show পড়ে তুমি বুঝতে পারবে না n কোনটা।Blocks, nested functions and referencing environmentBlock, nested function আর referencing environment
A block ({ ... } in C/Java) creates a new static scope. A local name hides (shadows) an outer variable with the same name. Python, Pascal, JavaScript and Ada allow nested functions, so the static parent can be another function.
The referencing environment of a statement is the set of all names visible there. In static scoping, it is the local names plus all names of its static ancestors that are not hidden.
একটা block (C/Java-তে { ... }) নতুন static scope তৈরি করে। একই নামের local variable বাইরের variable-কে hide (shadow) করে। Python, Pascal, JavaScript আর Ada-তে nested function লেখা যায়, তাই static parent আরেকটা function-ও হতে পারে।
কোনো statement-এর referencing environment হলো সেখানে দেখা যায় এমন সব নামের সেট। Static scoping-এ এটা local নামগুলো আর static ancestor-দের সব নাম, যেগুলো hide হয়নি।
# Python: nested function, static scope
x = 5
def g():
return x * 2 # x -> global x (static parent of g is the module)
def h():
x = 1 # local to h; g cannot see it
return g()
print(h()) # prints 10 (static). Under dynamic scoping it would be 2.
def outer():
count = 0
def inner():
nonlocal count # static parent is outer
count += 1
return count
return inner
c = outer()
print(c(), c()) # 1 2 (a closure keeps outer's count alive)
4. Data Types and Type Systems4. Data Types আর Type Systems
A data type is a set of values plus the operations allowed on them. For example, int in Java = whole numbers from −231 to 231−1, with + − * / %.
Primitive vs composite types
- Primitive types are built in and not made from other types: integer, floating point, character, boolean. (Java has 8 primitives:
byte, short, int, long, float, double, char, boolean.) - Composite (structured) types are built from other types: arrays, strings, records (
struct), unions, tuples, lists, classes, pointers/references. - Enumeration types list all possible values by name:
enum Day {SAT, SUN, MON};
Data type হলো কিছু value-এর সেট আর সেগুলোর ওপর যেসব operation করা যায়। যেমন Java-তে int = −231 থেকে 231−1 পর্যন্ত পূর্ণসংখ্যা, সাথে + − * / %।
Primitive vs composite type
- Primitive type built-in, অন্য type দিয়ে তৈরি না: integer, floating point, character, boolean। (Java-তে 8টা primitive:
byte, short, int, long, float, double, char, boolean।) - Composite (structured) type অন্য type দিয়ে তৈরি: array, string, record (
struct), union, tuple, list, class, pointer/reference। - Enumeration type সব সম্ভাব্য value নাম দিয়ে লিখে রাখে:
enum Day {SAT, SUN, MON};
Strong vs weak typing, static vs dynamic typingStrong vs weak typing, static vs dynamic typing
These are two different questions. Do not mix them up.
- Static vs dynamic typing asks WHEN types are checked. Static = at compile time. Dynamic = at run time.
- Strong vs weak typing asks HOW STRICT the checking is. Strong = type errors are always caught; the language does not silently mix unrelated types. Weak = the language quietly converts or reinterprets values, so some type errors slip through.
এগুলো দুটো আলাদা প্রশ্ন। গুলিয়ে ফেলো না।
- Static vs dynamic typing জিজ্ঞেস করে type কখন check হয়। Static = compile time-এ। Dynamic = run time-এ।
- Strong vs weak typing জিজ্ঞেস করে checking কতটা কড়া। Strong = type error সবসময় ধরা পড়ে; language চুপচাপ সম্পর্কহীন type মেশায় না। Weak = language চুপচাপ value convert বা অন্যভাবে পড়ে ফেলে, তাই কিছু type error ফসকে যায়।
| Language | Static / DynamicStatic / Dynamic | Strong / WeakStrong / Weak | Evidenceপ্রমাণ |
|---|---|---|---|
| C | Static | Weak | Unions, pointer casts, and void* let you read an int as a float. No array bound check.Union, pointer cast আর void* দিয়ে একটা int-কে float হিসেবে পড়া যায়। Array bound check নেই। |
| C++ | Static | Weak-ish (safer than C)কিছুটা weak (C-এর চেয়ে নিরাপদ) | Keeps C's unions and casts for compatibility.Compatibility-র জন্য C-এর union আর cast রেখে দিয়েছে। |
| Java | Static | Strong | int x = "5"; is a compile error. Bad casts throw ClassCastException. Array bounds are checked.int x = "5"; compile error। ভুল cast করলে ClassCastException। Array bound check হয়। |
| Python | Dynamic | Strong | "5" + 3 → TypeError at run time."5" + 3 → run time-এ TypeError। |
| JavaScript | Dynamic | Weak | "5" + 3 → "53", "5" - 3 → 2. Silent coercion."5" + 3 → "53", "5" - 3 → 2। চুপচাপ coercion। |
| Haskell / ML | Static (with type inference)Static (type inference সহ) | Strong | You rarely write types, yet every type is checked at compile time.Type প্রায় লিখতেই হয় না, তবু compile time-এ সব type check হয়। |
// JavaScript (weak, dynamic) — verified with Node.js
"5" + 3 // "53" (+ with a string means concatenation)
"5" - 3 // 2 (- forces a number)
"5" * "2" // 10
1 + true // 2 (true becomes 1)
# Python (strong, dynamic)
"5" + 3 # TypeError: can only concatenate str (not "int") to str
"5" * 2 # "55" (repetition is a defined str operation, not coercion)
int("5") + 3 # 8 (explicit conversion is fine)
Type conversion: coercion vs castType conversion: coercion vs cast
- Implicit conversion = coercion: the compiler converts automatically. In
3 + 2.5, C/Java change3to3.0first. This is a widening conversion (int → double): safe, no information lost. - Explicit conversion = cast: the programmer asks for it:
(int) 3.99→3. This is usually a narrowing conversion (double → int): may lose information. - Java allows implicit widening only.
int x = 3.5;is a compile error; you must writeint x = (int) 3.5;. C allows both silently (maybe with a warning).
More coercions = less reliable (errors are hidden). That is why Ada and ML have almost no coercion.
- Implicit conversion = coercion: compiler নিজে থেকেই convert করে।
3 + 2.5-এ C/Java আগে3-কে3.0বানায়। এটা widening conversion (int → double): নিরাপদ, কোনো তথ্য হারায় না। - Explicit conversion = cast: programmer নিজে চায়:
(int) 3.99→3। এটা সাধারণত narrowing conversion (double → int): তথ্য হারাতে পারে। - Java শুধু widening implicit-ভাবে করতে দেয়।
int x = 3.5;compile error; লিখতে হবেint x = (int) 3.5;। C দুটোই চুপচাপ করতে দেয় (হয়তো warning দিয়ে)।
যত বেশি coercion, তত কম reliable (error লুকিয়ে যায়)। এজন্যই Ada আর ML-এ প্রায় কোনো coercion নেই।
/* Java — verified */
byte b = (byte) 130; // narrowing: 130 does not fit in -128..127
System.out.println(b); // -126 (130 - 256)
double d = 7 / 2; // int division FIRST (3), then widened to 3.0
double e = 7 / 2.0; // 2 is coerced to 2.0, result 3.5
Type equivalence: name vs structuralType equivalence: name vs structural
When are two types "the same"?
- Name type equivalence — two variables have the same type only if they are declared with the same type name. Easy to implement, very strict. Used for C
structs, Java classes, Ada. - Structure type equivalence — two types are the same if they have the same structure (same fields/components in the same order). More flexible but harder to check, and it can treat
CelsiusandFahrenheitas the same (not what you want).
দুটো type কখন "একই"?
- Name type equivalence — দুটো variable একই type শুধু তখনই, যখন তারা একই type name দিয়ে declare করা। Implement করা সহজ, খুব কড়া। C
struct, Java class, Ada-তে ব্যবহার হয়। - Structure type equivalence — দুটো type একই যদি তাদের structure একই হয় (একই field/component একই order-এ)। বেশি flexible কিন্তু check করা কঠিন, আর এটা
CelsiusআরFahrenheit-কে একই ধরে নিতে পারে (যেটা আমরা চাই না)।
struct A { int x; float y; };
struct B { int x; float y; };
struct A p; struct B q;
p = q; // C: ERROR — name equivalence for structs (A and B are different names)
// Under structural equivalence this would be allowed.
typedef int Meter; Meter m = 5; int k = m; // OK in C: typedef is only a new NAME for int
Arrays: four kinds by binding of size and storageArray: size আর storage binding অনুযায়ী চার ধরন
| Kind | Size fixed?Size ঠিক কখন? | Storage fromStorage কোথা থেকে | ExampleExample |
|---|---|---|---|
| Static | Compile timeCompile time | Static area (before run)Static area (চালানোর আগে) | static int a[10]; (C) |
| Fixed stack-dynamic | Compile timeCompile time | Stack, at declarationStack, declaration-এর সময় | local int a[10]; in a C functionC function-এর local int a[10]; |
| Stack-dynamic | At run time, then fixedRun time-এ, তারপর স্থির | Stack | C99 VLA: int a[n];, AdaC99 VLA: int a[n];, Ada |
| Fixed heap-dynamic | At run time, then fixedRun time-এ, তারপর স্থির | Heap | malloc(n * sizeof(int)), Java new int[n] |
| Heap-dynamic | Can grow/shrink any timeযেকোনো সময় বাড়ে/কমে | Heap | Python list, Java ArrayList, C++ vector, JS arraysPython list, Java ArrayList, C++ vector, JS array |
Address formula (row-major, like C): for a[i][j] with n columns and element size s: address = base + (i × n + j) × s. Fortran and MATLAB are column-major: base + (j × m + i) × s for m rows. (Detailed memory layout in Chapter 01.)
Address formula (row-major, C-এর মতো): n column আর element size s হলে a[i][j]-এর জন্য: address = base + (i × n + j) × s। Fortran আর MATLAB column-major: m row হলে base + (j × m + i) × s। (বিস্তারিত memory layout Chapter 01-এ।)
Records, unions, pointers and referencesRecord, union, pointer আর reference
- Record — a group of named fields that can have different types (C
struct, Pascalrecord). Fields are accessed by name:s.cgpa. (Arrays are same type, accessed by index.) - Union — fields share the same memory; only one is valid at a time. Size = size of the largest field. A free union (C) has no type check, so it breaks type safety. A discriminated union (Ada, ML) has a tag field that says which member is valid.
- Pointer — holds a memory address. Can do arithmetic (
p + 1), can beNULL, can be changed to point elsewhere. C/C++. - Reference — an alias for an existing object. C++ references (
int &r = x;) must be initialized and never re-seated; no arithmetic. Java/Python variables of object type are references, and you cannot do pointer arithmetic on them — safer.
- Record — কিছু নামওয়ালা field-এর group, যাদের type আলাদা হতে পারে (C
struct, Pascalrecord)। Field নাম দিয়ে access হয়:s.cgpa। (Array-তে সব element একই type, index দিয়ে access।) - Union — সব field একই memory share করে; একসাথে শুধু একটাই valid। Size = সবচেয়ে বড় field-এর size। Free union (C)-এ type check নেই, তাই type safety ভাঙে। Discriminated union (Ada, ML)-এ একটা tag field থাকে যা বলে কোন member valid।
- Pointer — memory address রাখে। Arithmetic করা যায় (
p + 1),NULLহতে পারে, অন্য জায়গায় point করানো যায়। C/C++। - Reference — existing object-এর একটা alias। C++ reference (
int &r = x;) initialize করতেই হয়, পরে আর অন্য object-এ বসানো যায় না; arithmetic নেই। Java/Python-এর object-type variable-গুলো reference, আর এগুলোর ওপর pointer arithmetic করা যায় না — বেশি নিরাপদ।
Dangling reference/pointer — a pointer that still points to memory that has been freed. Example:
int *p = malloc(4); free(p); *p = 5; or returning the address of a local variable. Memory leak (lost heap-dynamic variable) — heap memory that is still allocated but no pointer reaches it, so it can never be freed. Example:
p = malloc(4); p = malloc(4); (first block is lost).Garbage collection (Java, Python) removes most leaks and all dangling pointers. More C examples in Chapter 01, Memory Concepts.
Dangling reference/pointer — এমন pointer যা এখনো এমন memory-কে point করছে যেটা free হয়ে গেছে। উদাহরণ:
int *p = malloc(4); free(p); *p = 5; অথবা local variable-এর address return করা।Memory leak (lost heap-dynamic variable) — heap memory এখনো allocated, কিন্তু কোনো pointer সেখানে পৌঁছায় না, তাই আর কখনো free করা যাবে না। উদাহরণ:
p = malloc(4); p = malloc(4); (প্রথম block হারিয়ে গেল)।Garbage collection (Java, Python) বেশিরভাগ leak আর সব dangling pointer দূর করে। আরও C example আছে Chapter 01, Memory Concepts-এ।
5. Expressions and Control Structures5. Expressions আর Control Structures
Precedence and associativityPrecedence আর associativity
Precedence decides which operator goes first when different operators meet: 2 + 3 * 4 = 2 + 12 = 14, because * is higher than +.
Associativity decides the order when operators of the same precedence meet. Most binary operators are left-associative: 10 - 4 - 3 = (10 - 4) - 3 = 3. A few are right-associative: assignment (a = b = 5), exponent (** in Python, Fortran, Ruby), and C's unary operators and ?:.
Precedence ঠিক করে আলাদা operator পাশাপাশি থাকলে কোনটা আগে: 2 + 3 * 4 = 2 + 12 = 14, কারণ *-এর precedence +-এর চেয়ে বেশি।
Associativity ঠিক করে একই precedence-এর operator পাশাপাশি থাকলে কোন দিক থেকে হিসাব হবে। বেশিরভাগ binary operator left-associative: 10 - 4 - 3 = (10 - 4) - 3 = 3। কয়েকটা right-associative: assignment (a = b = 5), exponent (Python, Fortran, Ruby-তে **), আর C-এর unary operator আর ?:।
# Python — verified
print(2 ** 3 ** 2) # 512 = 2 ** (3 ** 2) = 2 ** 9 (right-assoc)
print(-2 ** 2) # -4 = -(2 ** 2) (** binds tighter than unary minus)
print(10 - 4 - 3) # 3 (left-assoc)
/* C — verified */
int x = 10 - 4 - 3 * 2 / 4; // 3*2=6, 6/4=1 (int), 10-4=6, 6-1 = 5
printf("%d", 5 > 3 > 1); // (5>3) is 1, then 1 > 1 is 0 -> prints 0
# But Python CHAINS comparisons:
print(5 > 3 > 1) # True, means (5 > 3) and (3 > 1)
// JavaScript: 3 > 2 > 1 -> (true) > 1 -> 1 > 1 -> false
a > b > c gives different answers in C/Java/JavaScript vs Python. In C and JS it is left-associative (compare a boolean 0/1 with c). In Java it does not even compile (boolean > int). In Python it is a chained comparison, like maths.a > b > c C/Java/JavaScript আর Python-এ আলাদা উত্তর দেয়। C আর JS-এ এটা left-associative (boolean 0/1-কে c-এর সাথে তুলনা)। Java-তে compile-ই হয় না (boolean > int)। Python-এ এটা chained comparison, অঙ্কের মতো।Short-circuit evaluationShort-circuit evaluation
In A && B, if A is false, the result must be false — so B is not evaluated at all. In A || B, if A is true, B is skipped. This is short-circuit evaluation. C, C++, Java, JavaScript use it for && and ||. Python uses it for and / or. Java's & and | on booleans do not short-circuit.
It is useful for safety: if (p != NULL && p->val > 0) never touches a NULL pointer. if (i < n && a[i] != key) never goes out of bounds.
A && B-তে A false হলে result তো false-ই — তাই B একদমই evaluate হয় না। A || B-তে A true হলে B বাদ। এটাই short-circuit evaluation। C, C++, Java, JavaScript && আর ||-এ এটা করে। Python করে and / or-এ। Java-তে boolean-এর ওপর & আর | short-circuit করে না।
এটা নিরাপত্তার জন্য কাজে লাগে: if (p != NULL && p->val > 0) কখনো NULL pointer ছোঁয় না। if (i < n && a[i] != key) কখনো bound-এর বাইরে যায় না।
m and n after each line? (Each line starts again with m = 0, n = 5.)m আর n কত? (প্রতিটা line আবার m = 0, n = 5 দিয়ে শুরু।)if (m++ || n++) {} // m++ gives 0 (false), so n++ runs -> m = 1, n = 6
if (++m || n++) {} // ++m gives 1 (true), n++ is SKIPPED -> m = 1, n = 5
if (m && n++) {} // m is 0 (false), n++ is SKIPPED -> m = 0, n = 5
Side effects and evaluation orderSide effect আর evaluation order
A functional side effect happens when a function changes a non-local variable or a parameter, besides returning a value. Then the order of evaluating operands matters.
Example: a = 10; b = a + fun(&a); where fun sets a = 20 and returns 5. If a is read first: b = 10 + 5 = 15. If fun runs first: b = 20 + 5 = 25. In C the order is unspecified. Java fixes left-to-right order, so Java gives 15.
Also, in C, i = i++ + ++i; is undefined behaviour (a variable changed twice without a sequence point). Any output is "correct". If an exam asks it, write "undefined behaviour".
Functional side effect হয় যখন কোনো function value return করার পাশাপাশি একটা non-local variable বা parameter বদলে দেয়। তখন operand evaluate করার order গুরুত্বপূর্ণ হয়ে যায়।
উদাহরণ: a = 10; b = a + fun(&a); যেখানে fun a = 20 করে আর 5 return করে। আগে a পড়লে: b = 10 + 5 = 15। আগে fun চললে: b = 20 + 5 = 25। C-তে order unspecified। Java left-to-right order ঠিক করে দিয়েছে, তাই Java-তে 15।
আবার, C-তে i = i++ + ++i; হলো undefined behaviour (sequence point ছাড়া একটা variable দুবার বদলানো)। যেকোনো output-ই "ঠিক"। Exam-এ এলে লিখবে "undefined behaviour"।
Assignment formsAssignment-এর ধরন
| Form | ExampleExample | Meaningমানে |
|---|---|---|
| Simple | x = 5 | Store 5 in x. (Pascal/Ada use :=.)x-এ 5 রাখো। (Pascal/Ada-তে :=।) |
| Compound | x += 3 | x = x + 3 |
| Unary | x++, ++x | Post: use old value then add. Pre: add then use.Post: আগে পুরোনো value ব্যবহার, পরে যোগ। Pre: আগে যোগ, পরে ব্যবহার। |
| Multiple target | a = b = 0 | Right-assoc: a = (b = 0). Assignment is an expression in C/Java.Right-assoc: a = (b = 0)। C/Java-তে assignment নিজেও একটা expression। |
| Conditional | x = (a > b) ? a : b | Pick one value by a condition.Condition দেখে একটা value নাও। |
| Tuple / parallel | a, b = b, a | Python swap in one line (right side is evaluated first).এক লাইনে Python swap (ডান পাশ আগে evaluate হয়)। |
if (x = 0) in C assigns 0 and the condition is always false. Java refuses to compile it (condition must be boolean) — a reliability win for Java.if (x = 0) 0 assign করে আর condition সবসময় false। Java এটা compile-ই করে না (condition boolean হতে হবে) — Java-র reliability-র জয়।Selection and iteration across languagesবিভিন্ন language-এ selection আর iteration
| ConstructConstruct | C / C++ / Java | Python | NoteNote |
|---|---|---|---|
| Two-way selection | if (c) {...} else {...} | if c: ... else: ... | Python uses indentation, not braces.Python brace না, indentation ব্যবহার করে। |
| Multi-way selection | switch (x) { case 1: ... break; } | if/elif/else, match (3.10+) | Without break, C/Java fall through to the next case.break না দিলে C/Java পরের case-এ fall through করে। |
| Counter loop | for (i = 0; i < n; i++) | for i in range(n): | Python's for walks over any iterable.Python-এর for যেকোনো iterable-এর ওপর ঘোরে। |
| Pretest loop | while (c) {...} | while c: | May run 0 times.0 বারও চলতে পারে। |
| Posttest loop | do {...} while (c); | none (use while True: ... if not c: break)নেই (while True: ... if not c: break ব্যবহার করো) | Runs at least once.অন্তত একবার চলে। |
| Iterator loop | for (int v : arr) (Java), for (auto v : vec) (C++) | for v in lst: | No index needed.Index লাগে না। |
Loop else | — | for ... else: | Python only: else runs if the loop ended without break.শুধু Python: loop break ছাড়া শেষ হলে else চলে। |
The old goto statement is avoided in structured programming (Dijkstra, "Go To Statement Considered Harmful", 1968). Java reserves goto as a keyword but does not allow it. The structured program theorem (Böhm–Jacopini) says any program can be written with only sequence, selection and iteration.
Structured programming-এ পুরোনো goto statement এড়িয়ে চলা হয় (Dijkstra, "Go To Statement Considered Harmful", 1968)। Java goto-কে keyword হিসেবে রেখেছে কিন্তু ব্যবহার করতে দেয় না। Structured program theorem (Böhm–Jacopini) বলে যে কোনো program শুধু sequence, selection আর iteration দিয়ে লেখা যায়।
Recursion vs iteration (language view)Recursion vs iteration (language-এর দৃষ্টিতে)
- Every recursive call creates a new activation record on the stack (see Section 6). So recursion uses O(depth) extra memory; a loop uses O(1).
- Too deep recursion causes stack overflow. Python stops at about 1000 levels by default (
RecursionError). - Tail recursion: the recursive call is the very last action. Functional languages (Scheme, Haskell) and some C compilers turn it into a loop (tail-call optimization), so no extra stack is used. Java and Python do not do this.
- Functional languages have no loops at all — recursion is the only way to repeat.
- প্রতিটা recursive call stack-এ একটা নতুন activation record তৈরি করে (Section 6 দেখো)। তাই recursion O(depth) বাড়তি memory নেয়; loop নেয় O(1)।
- বেশি গভীর recursion হলে stack overflow হয়। Python default-এ প্রায় 1000 level-এ থামে (
RecursionError)। - Tail recursion: recursive call-টাই একদম শেষ কাজ। Functional language (Scheme, Haskell) আর কিছু C compiler এটাকে loop-এ বদলে দেয় (tail-call optimization), তাই বাড়তি stack লাগে না। Java আর Python এটা করে না।
- Functional language-এ loop-ই নেই — repeat করার একমাত্র উপায় recursion।
// Not tail recursive: after the call returns we still multiply by n
int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); }
// Tail recursive: the call is the last thing; 'acc' carries the answer
int factT(int n, int acc) { return (n <= 1) ? acc : factT(n - 1, n * acc); }
// factT(4, 1) -> factT(3, 4) -> factT(2, 12) -> factT(1, 24) -> 24
6. Subprograms and Parameter Passing6. Subprograms আর Parameter Passing
A subprogram is a function or procedure. A function returns a value; a procedure (a void function in C) does not.
- Formal parameters — the names in the subprogram header: in
int add(int a, int b),aandbare formal. - Actual parameters (arguments) — the values/variables written in the call: in
add(x, 5),xand5are actual. - Positional matching: 1st actual → 1st formal. Keyword matching (Python, Ada):
add(b=5, a=x). Default values:def add(a, b=0).
Three semantic models
- In mode — data goes into the subprogram only.
- Out mode — data comes back to the caller only.
- In-out mode — both ways.
Subprogram মানে function বা procedure। Function value return করে; procedure (C-এর void function) করে না।
- Formal parameter — subprogram header-এ লেখা নাম:
int add(int a, int b)-এaআরbformal। - Actual parameter (argument) — call-এ লেখা value/variable:
add(x, 5)-এxআর5actual। - Positional matching: ১ম actual → ১ম formal। Keyword matching (Python, Ada):
add(b=5, a=x)। Default value:def add(a, b=0)।
তিনটা semantic model
- In mode — data শুধু subprogram-এর ভেতরে যায়।
- Out mode — data শুধু caller-এর কাছে ফেরত আসে।
- In-out mode — দুই দিকেই।
The four classic parameter-passing methodsচারটা classic parameter-passing method
| Method | How it worksকীভাবে কাজ করে | Mode | Used inকোথায় ব্যবহার |
|---|---|---|---|
| Pass-by-value | The value of the actual is copied into the formal. Changes to the formal do not affect the caller.Actual-এর value formal-এ copy হয়। Formal বদলালে caller-এর কিছু বদলায় না। | In | C (all), Java (all — even object references are copied), Python (object reference copied)C (সব), Java (সব — object reference-ও copy হয়), Python (object reference copy হয়) |
| Pass-by-result | Formal starts empty; its final value is copied back to the actual at return.Formal খালি থেকে শুরু; return-এ তার শেষ value actual-এ copy হয়। | Out | Ada out, C# out |
| Pass-by-value-result (copy-in copy-out) | Copy the value in at the call; work on the local copy; copy the final value back to the actual's address at return.Call-এর সময় value copy করে ভেতরে আনো; local copy-তে কাজ করো; return-এ শেষ value actual-এর address-এ copy করে ফেরত দাও। | In-out | Fortran (some), Ada in out (scalars) |
| Pass-by-reference | The address of the actual is passed. The formal is an alias. Every change is instantly a change to the caller's variable.Actual-এর address pass হয়। Formal একটা alias। প্রতিটা পরিবর্তন সাথে সাথে caller-এর variable-এ হয়। | In-out | C++ &, C# ref, Pascal var, C simulated with pointersC++ &, C# ref, Pascal var, C-তে pointer দিয়ে simulate |
| Pass-by-name | The actual parameter expression text is substituted for the formal. It is re-evaluated every time the formal is used (implemented with a "thunk").Formal-এর জায়গায় actual parameter-এর expression text বসিয়ে দেওয়া হয়। Formal যতবার ব্যবহার হয়, ততবার আবার evaluate হয় ("thunk" দিয়ে implement)। | In-out | ALGOL 60, Scala (by-name params), similar to C macrosALGOL 60, Scala (by-name param), C macro-র মতো |
i and a are global.i আর a global।int i = 0;
int a[3] = {5, 10, 15};
void f(int x) {
i = i + 1; // step 1
a[0] = 100; // step 2
x = x + 1; // step 3
}
main() {
f(a[i]); // the actual parameter is a[i], and i = 0 now
print(i, a[0], a[1], a[2]);
}
(1) Pass-by-value. At the call, x = a[0] = 5 (a copy). Step 1: i = 1. Step 2: a[0] = 100. Step 3: x = 6, but x is only a local copy, so nothing else changes.
Output: i=1, a = 100 10 15
(2) Pass-by-reference. At the call, x becomes an alias of a[0] (the address is fixed at the call, when i = 0). Step 1: i = 1. Step 2: a[0] = 100, so x is also 100. Step 3: x = x + 1 means a[0] = 100 + 1 = 101.
Output: i=1, a = 101 10 15
(3) Pass-by-value-result. At the call, x = 5 (copy in) and we remember the address of a[0]. Step 1: i = 1. Step 2: a[0] = 100 (the local x does not see this). Step 3: x = 6. At return, copy out: a[0] = x = 6 — this overwrites the 100.
Output: i=1, a = 6 10 15
(4) Pass-by-name. Every x in the body is replaced by the text a[i]. Step 1: i = 1. Step 2: a[0] = 100. Step 3: a[i] = a[i] + 1, and now i is 1, so a[1] = 10 + 1 = 11.
Output: i=1, a = 100 11 15
(1) Pass-by-value। Call-এর সময় x = a[0] = 5 (একটা copy)। Step 1: i = 1। Step 2: a[0] = 100। Step 3: x = 6, কিন্তু x শুধু local copy, তাই আর কিছু বদলায় না।
Output: i=1, a = 100 10 15
(2) Pass-by-reference। Call-এর সময় x হয়ে যায় a[0]-এর alias (address call-এর সময়েই ঠিক হয়, যখন i = 0)। Step 1: i = 1। Step 2: a[0] = 100, তাই x-ও 100। Step 3: x = x + 1 মানে a[0] = 100 + 1 = 101।
Output: i=1, a = 101 10 15
(3) Pass-by-value-result। Call-এর সময় x = 5 (copy in) আর a[0]-এর address মনে রাখা হয়। Step 1: i = 1। Step 2: a[0] = 100 (local x এটা দেখে না)। Step 3: x = 6। Return-এর সময় copy out: a[0] = x = 6 — এটা 100-কে overwrite করে।
Output: i=1, a = 6 10 15
(4) Pass-by-name। Body-র প্রতিটা x-এর জায়গায় text a[i] বসে। Step 1: i = 1। Step 2: a[0] = 100। Step 3: a[i] = a[i] + 1, আর এখন i = 1, তাই a[1] = 10 + 1 = 11।
Output: i=1, a = 100 11 15
| Method | i | a[0] | a[1] | a[2] |
|---|---|---|---|---|
| Pass-by-value | 1 | 100 | 10 | 15 |
| Pass-by-reference | 1 | 101 | 10 | 15 |
| Pass-by-value-result | 1 | 6 | 10 | 15 |
| Pass-by-name | 1 | 100 | 11 | 15 |
a[i]).a[i] আবার পড়ার thunk)।a[i] when i changes. (3) If the question does not say when the copy-back address is computed, state your assumption (usually "at call time").i বদলালে a[i]। (৩) প্রশ্নে copy-back address কখন হিসাব হয় না বললে, তোমার assumption লিখে দাও (সাধারণত "call time-এ")।p.x = 5 is seen by the caller), but p = new Point() inside the method does not change the caller's variable. That is why a Java swap(Integer a, Integer b) cannot swap the caller's variables. Python works the same way ("pass by object reference" / "call by sharing").p.x = 5 caller দেখতে পায়), কিন্তু method-এর ভেতরে p = new Point() করলে caller-এর variable বদলায় না। এজন্যই Java-তে swap(Integer a, Integer b) caller-এর variable swap করতে পারে না। Python-ও একইভাবে কাজ করে ("pass by object reference" / "call by sharing")।Activation records and the run-time stackActivation record আর run-time stack
Each time a subprogram is called, the system pushes an activation record (AR), also called a stack frame, on the run-time stack. When it returns, the AR is popped. A typical AR holds:
- Return address — where to continue in the caller after return.
- Dynamic link — pointer to the caller's AR (to restore the stack; also how dynamic scoping searches).
- Static link — pointer to the AR of the static parent (the enclosing function in the source). Needed only in languages with nested functions (Pascal, Ada, Python closures) to find non-local variables under static scoping.
- Parameters — values or addresses passed in.
- Local variables (stack-dynamic) and temporary values.
- Sometimes a slot for the return value and saved registers.
Because each call gets its own AR, recursion works: fact(3), fact(2), fact(1) each have their own n.
প্রতিবার কোনো subprogram call হলে system run-time stack-এ একটা activation record (AR) push করে, যাকে stack frame-ও বলে। Return করলে AR pop হয়। সাধারণ একটা AR-এ থাকে:
- Return address — return-এর পরে caller-এর কোথা থেকে আবার চলবে।
- Dynamic link — caller-এর AR-এর pointer (stack আগের অবস্থায় ফেরাতে; dynamic scoping এভাবেই খোঁজে)।
- Static link — static parent-এর (source-এ যে function-এর ভেতরে লেখা) AR-এর pointer। শুধু nested function থাকা language-এ (Pascal, Ada, Python closure) static scoping-এ non-local variable খুঁজতে লাগে।
- Parameters — pass করা value বা address।
- Local variables (stack-dynamic) আর temporary value।
- কখনো return value-এর জায়গা আর saved register।
প্রতিটা call নিজের AR পায় বলেই recursion কাজ করে: fact(3), fact(2), fact(1) — প্রত্যেকের নিজের n।
int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1); // return point "RA1"
}
int main() {
int r = fact(3); // return point "RA0"
printf("%d\n", r); // 6
}
| Static link | Dynamic link | |
|---|---|---|
| Points toকাকে point করে | AR of the static parent (enclosing function in the source)Static parent-এর AR (source-এ ঘিরে থাকা function) | AR of the callerCaller-এর AR |
| Used forকাজে লাগে | Finding non-local variables under static scopingStatic scoping-এ non-local variable খুঁজতে | Restoring the stack on return; non-local lookup under dynamic scopingReturn-এ stack ফেরাতে; dynamic scoping-এ non-local খুঁজতে |
| Needed in C?C-তে লাগে? | No — C has no nested functions (non-locals are just globals)না — C-তে nested function নেই (non-local মানেই global) | Yes (the saved frame pointer)হ্যাঁ (saved frame pointer) |
Overloaded and generic subprogramsOverloaded আর generic subprogram
- Overloaded subprogram — same name, different parameter profile (number/types/order of parameters). The compiler picks the right one at compile time. Return type alone is not enough to overload in C++/Java. C does not support overloading; Python does not either (a later
defjust replaces the earlier one). - Generic (polymorphic) subprogram — one piece of code that works for many types. C++ templates, Java generics (
<T>), C# generics. This is called parametric polymorphism. (Overloading is ad hoc polymorphism; inheritance-based overriding is subtype polymorphism — see Chapter 02.)
- Overloaded subprogram — একই নাম, আলাদা parameter profile (parameter-এর সংখ্যা/type/order)। Compiler compile time-এ ঠিকটা বেছে নেয়। C++/Java-তে শুধু return type আলাদা হলে overload হয় না। C overloading support করে না; Python-ও না (পরের
defআগেরটাকে শুধু replace করে)। - Generic (polymorphic) subprogram — একটাই code যা অনেক type-এর জন্য কাজ করে। C++ template, Java generics (
<T>), C# generics। একে বলে parametric polymorphism। (Overloading হলো ad hoc polymorphism; inheritance-ভিত্তিক overriding হলো subtype polymorphism — Chapter 02 দেখো।)
// C++ — verified output: "7 2.5 z" and "16 15 3.14"
template <typename T>
T maxOf(T a, T b) { return a > b ? a : b; } // generic
int area(int s) { return s * s; } // overloaded
int area(int l, int w) { return l * w; }
double area(double r) { return 3.14 * r * r; }
cout << maxOf(3, 7) << " " << maxOf(2.5, 1.5) << " " << maxOf('a', 'z');
cout << area(4) << " " << area(3, 5) << " " << area(1.0);
// Java generic method
static <T extends Comparable<T>> T maxOf(T a, T b) { return a.compareTo(b) > 0 ? a : b; }
Closures: a subprogram plus the referencing environment where it was defined. In Python/JavaScript a nested function can return and still use its parent's variables (see the outer/inner example in Section 3). The parent's variables must then live on the heap, not the stack.
Closure: একটা subprogram আর যেখানে এটা define হয়েছে সেখানকার referencing environment — একসাথে। Python/JavaScript-এ nested function return হয়ে যাওয়ার পরেও parent-এর variable ব্যবহার করতে পারে (Section 3-এর outer/inner example দেখো)। তখন parent-এর variable-গুলো stack-এ না, heap-এ রাখতে হয়।
7. Memory Management and Exceptions7. Memory Management আর Exceptions
Static, stack and heap allocation — recapStatic, stack আর heap allocation — recap
| Area | What lives thereকী থাকে | Allocated / freedAllocate / free কখন | SpeedSpeed |
|---|---|---|---|
| Static | Globals, static variables, constants, codeGlobal, static variable, constant, code | At load time / at program endLoad time-এ / program শেষে | Fastestসবচেয়ে দ্রুত |
| Stack | Activation records: parameters, locals, return addressActivation record: parameter, local, return address | Automatically on call / return (LIFO)Call / return-এ আপনা-আপনি (LIFO) | Very fast (move stack pointer)খুব দ্রুত (stack pointer সরানো) |
| Heap | Objects created with new/malloc, dynamic structuresnew/malloc দিয়ে তৈরি object, dynamic structure | Any order; freed by free/delete or by a garbage collectorযেকোনো order-এ; free/delete বা garbage collector দিয়ে free | Slower; can fragmentধীর; fragment হতে পারে |
Picture of a C process memory layout (text, data, BSS, heap, stack) is in Chapter 01, Memory Concepts. OS-level paging is in Chapter 14.
C process-এর memory layout-এর ছবি (text, data, BSS, heap, stack) আছে Chapter 01, Memory Concepts-এ। OS-level paging আছে Chapter 14-এ।
Garbage collection (GC)Garbage collection (GC)
Garbage = heap objects that the program can no longer reach from any root (globals, local variables on the stack, registers). A garbage collector finds garbage and frees it automatically. Java, Python, C#, JavaScript, Lisp, Go have GC. C and C++ do not (C++ uses destructors and smart pointers instead).
1) Reference counting (eager)
Every object keeps a counter: how many pointers point to it. When a pointer is added, count +1. When a pointer is removed, count −1. When the count becomes 0, free the object immediately.
- Plus: memory is freed at once, work is spread out (no long pauses).
- Minus: extra space for each counter; extra time on every pointer assignment; and it cannot free cycles. If A points to B and B points to A, and nothing else points to them, both counts stay at 1 forever → memory leak.
- Python (CPython) uses reference counting plus a separate cycle detector to fix this.
2) Mark-and-sweep (lazy / tracing)
Let garbage pile up. When memory runs low, stop the program and run two phases:
- Mark: start from every root; follow every pointer (like DFS on a graph); mark every object you reach as "alive".
- Sweep: walk through the whole heap; every unmarked object is garbage → put it back on the free list. Clear the marks for next time.
- Plus: handles cycles correctly; no cost on every assignment.
- Minus: "stop-the-world" pauses; the heap can become fragmented (small free holes).
3) Copying collector
Split the heap into two halves: from-space and to-space. Allocate only in from-space. When it is full, copy every reachable object into to-space (packed together), then swap the roles. Everything left behind is garbage.
- Plus: no fragmentation (objects are compacted); very fast allocation (just bump a pointer); time depends only on live objects.
- Minus: only half the memory is usable at a time; pointers must be updated after copying.
Modern JVMs use generational GC: most objects die young, so a small "young generation" is collected often with copying, and the "old generation" rarely with mark-sweep-compact.
Garbage = heap-এর সেইসব object যেগুলোতে program আর কোনো root (global, stack-এর local variable, register) থেকে পৌঁছাতে পারে না। Garbage collector garbage খুঁজে বের করে আপনা-আপনি free করে। Java, Python, C#, JavaScript, Lisp, Go-তে GC আছে। C আর C++-এ নেই (C++ এর বদলে destructor আর smart pointer ব্যবহার করে)।
১) Reference counting (eager)
প্রতিটা object একটা counter রাখে: কয়টা pointer তাকে point করছে। Pointer যোগ হলে count +1। Pointer সরে গেলে count −1। Count 0 হলে object-টা সাথে সাথে free।
- সুবিধা: memory সাথে সাথে free হয়, কাজ ছড়িয়ে থাকে (লম্বা pause নেই)।
- অসুবিধা: প্রতিটা counter-এর জন্য বাড়তি জায়গা; প্রতিটা pointer assignment-এ বাড়তি সময়; আর এটা cycle free করতে পারে না। A যদি B-কে আর B যদি A-কে point করে, আর বাইরে থেকে কেউ তাদের point না করে, তাহলে দুজনের count চিরকাল 1 থাকে → memory leak।
- Python (CPython) reference counting-এর সাথে আলাদা একটা cycle detector ব্যবহার করে এই সমস্যা ঠিক করতে।
২) Mark-and-sweep (lazy / tracing)
Garbage জমতে দাও। Memory কমে গেলে program থামিয়ে দুইটা phase চালাও:
- Mark: প্রতিটা root থেকে শুরু করো; প্রতিটা pointer অনুসরণ করো (graph-এ DFS-এর মতো); যেখানে পৌঁছাও সেই object-কে "alive" mark করো।
- Sweep: পুরো heap ঘুরে দেখো; যে object unmarked সেটা garbage → free list-এ ফেরত দাও। পরেরবারের জন্য mark মুছে দাও।
- সুবিধা: cycle ঠিকমতো handle করে; প্রতি assignment-এ খরচ নেই।
- অসুবিধা: "stop-the-world" pause; heap fragmented হয়ে যেতে পারে (ছোট ছোট ফাঁকা জায়গা)।
৩) Copying collector
Heap-কে দুই ভাগ করো: from-space আর to-space। শুধু from-space-এ allocate করো। ভরে গেলে প্রতিটা reachable object to-space-এ copy করো (গায়ে গায়ে সাজিয়ে), তারপর দুই ভাগের ভূমিকা বদলাও। যা পেছনে রয়ে গেল সব garbage।
- সুবিধা: fragmentation নেই (object-গুলো compact হয়); allocation খুব দ্রুত (শুধু একটা pointer বাড়ানো); সময় লাগে শুধু live object-এর ওপর।
- অসুবিধা: একসাথে memory-র মাত্র অর্ধেক ব্যবহার করা যায়; copy করার পরে pointer update করতে হয়।
আধুনিক JVM generational GC ব্যবহার করে: বেশিরভাগ object অল্প বয়সেই মারা যায়, তাই ছোট একটা "young generation" ঘন ঘন copying দিয়ে collect হয়, আর "old generation" মাঝে মাঝে mark-sweep-compact দিয়ে।
| Reference counting | Mark-and-sweep | Copying | |
|---|---|---|---|
| When it freesকখন free করে | Immediately (count = 0)সাথে সাথে (count = 0) | When memory runs lowMemory কমে গেলে | When from-space is fullFrom-space ভরে গেলে |
| CyclesCycle | NOT freed (leak)Free হয় না (leak) | FreedFree হয় | FreedFree হয় |
| PausesPause | Small, spread outছোট, ছড়ানো | Long (stop-the-world)লম্বা (stop-the-world) | Proportional to live dataLive data-র সমানুপাতিক |
| FragmentationFragmentation | Yesহ্যাঁ | Yes (unless compacted)হ্যাঁ (compact না করলে) | No (compacts)না (compact করে) |
| Memory overheadMemory overhead | A counter per objectপ্রতি object-এ একটা counter | A mark bit per objectপ্রতি object-এ একটা mark bit | Half the heap is idleHeap-এর অর্ধেক অলস থাকে |
Exception handlingException handling
An exception is an unusual event at run time (divide by zero, array index out of range, file not found, null pointer). The exception handler is the code that deals with it. Without exception handling, you would check error codes after every call (C style: if (fp == NULL) ...).
The model: raise → search → handle
- Code in a
tryblock raises / throws an exception. - The rest of the
tryblock is skipped. - The system looks for a matching
catch/exceptin the same function. If none matches, the function ends and the exception propagates to the caller (the stack unwinds, popping ARs), and so on up tomain. If nobody catches it, the program stops with an error message and stack trace. - A
finallyblock (Java, Python, C#) always runs — normal exit, exception, or evenreturn. Use it to close files/locks. C++ has nofinally; it uses destructors (RAII) instead. - After a handler finishes, execution continues after the whole try-catch (the termination model) — not back at the line that failed.
Exception হলো run time-এ অস্বাভাবিক কোনো ঘটনা (zero দিয়ে ভাগ, array index range-এর বাইরে, file পাওয়া যায়নি, null pointer)। যে code এটা সামলায় তাকে বলে exception handler। Exception handling না থাকলে প্রতিটা call-এর পরে error code check করতে হতো (C style: if (fp == NULL) ...)।
Model: raise → search → handle
tryblock-এর code একটা exception raise / throw করে।tryblock-এর বাকি অংশ skip হয়।- System একই function-এ মিলে যায় এমন
catch/exceptখোঁজে। না মিললে function শেষ হয়ে যায় আর exception caller-এর কাছে propagate করে (stack unwind হয়, AR pop হয়), এভাবেmainপর্যন্ত। কেউ catch না করলে program error message আর stack trace দিয়ে থেমে যায়। finallyblock (Java, Python, C#) সবসময় চলে — স্বাভাবিকভাবে বের হলে, exception হলে, এমনকিreturnহলেও। File/lock বন্ধ করতে এটা ব্যবহার করো। C++-এfinallyনেই; তার বদলে destructor (RAII) ব্যবহার হয়।- Handler শেষ হলে execution পুরো try-catch-এর পরে চলতে থাকে (termination model) — যে line-এ error হয়েছিল সেখানে ফেরে না।
// C++ Output:
double divide(int a, int b) { // 5
if (b == 0) throw runtime_error("b is zero"); // Error: b is zero
return (double)a / b; // end
}
int main() {
try {
cout << divide(10, 2) << endl;
cout << divide(1, 0) << endl; // throws here
cout << "not printed" << endl; // skipped
} catch (const runtime_error& e) {
cout << "Error: " << e.what() << endl;
}
cout << "end" << endl;
}
# Python Output:
def f(x): # ok
try: # cleanup
r = 10 / x # 5.0
except ZeroDivisionError: # div by zero
print("div by zero"); r = -1 # cleanup
else: # -1
print("ok") # runs only if NO exception
finally:
print("cleanup") # runs ALWAYS
return r
print(f(2)); print(f(0))
// Java: finally runs even when try has a return Output:
static int test() { // finally
try { return 1; } // 1
finally { System.out.println("finally"); }
}
System.out.println(test());
| C++ | Java | Python | |
|---|---|---|---|
| KeywordsKeyword | try / catch / throw | try / catch / finally / throw / throws | try / except / else / finally / raise |
| What can be thrownকী throw করা যায় | Any type (even int)যেকোনো type (এমনকি int) | Only Throwable objectsশুধু Throwable object | Only BaseException objectsশুধু BaseException object |
finally | No (use destructors)নেই (destructor ব্যবহার) | Yesআছে | Yesআছে |
| Checked exceptionsChecked exception | Noনেই | Yes — must catch or declare with throws (e.g. IOException). RuntimeExceptions are unchecked.আছে — catch করতে হবে বা throws দিয়ে declare করতে হবে (যেমন IOException)। RuntimeException unchecked। | Noনেই |
| Divide int by zeroInt-কে zero দিয়ে ভাগ | Undefined behaviour (usually crash), NOT an exceptionUndefined behaviour (সাধারণত crash), exception না | ArithmeticException | ZeroDivisionError |
catch (Exception e) before catch (ArithmeticException e) is a compile error ("already caught"). Java's order: Throwable → Error (don't catch) / Exception → RuntimeException (unchecked) / other checked exceptions.catch (ArithmeticException e)-এর আগে catch (Exception e) দিলে compile error ("already caught")। Java-র hierarchy: Throwable → Error (catch কোরো না) / Exception → RuntimeException (unchecked) / অন্য checked exception।Concurrency one-linersConcurrency এক লাইনে
- Thread — a light-weight unit of execution inside a process; threads share the process's heap and globals but each has its own stack.
- Race condition — two threads update shared data at the same time and the result depends on timing. Fix with mutual exclusion (locks, semaphores, monitors). Full detail in Chapter 14, Synchronization.
- Java:
Threadclass /Runnable,synchronizedmethods (a built-in monitor). C++11:std::thread,std::mutex. Python:threadingmodule, but the GIL lets only one thread run Python bytecode at a time (usemultiprocessingfor CPU work). - Deadlock — threads wait for each other forever (see Chapter 14, Deadlocks).
- Go uses goroutines and channels; Erlang uses message passing (no shared memory).
- Thread — process-এর ভেতরে হালকা একটা execution unit; thread-গুলো process-এর heap আর global share করে, কিন্তু প্রত্যেকের নিজের stack থাকে।
- Race condition — দুটো thread একই সময়ে shared data update করে আর result timing-এর ওপর নির্ভর করে। Mutual exclusion (lock, semaphore, monitor) দিয়ে ঠিক করা হয়। বিস্তারিত Chapter 14, Synchronization-এ।
- Java:
Threadclass /Runnable,synchronizedmethod (built-in monitor)। C++11:std::thread,std::mutex। Python:threadingmodule, কিন্তু GIL একসাথে শুধু একটা thread-কে Python bytecode চালাতে দেয় (CPU-র কাজের জন্যmultiprocessingব্যবহার করো)। - Deadlock — thread-গুলো একে অপরের জন্য চিরকাল অপেক্ষা করে (Chapter 14, Deadlocks দেখো)।
- Go ব্যবহার করে goroutine আর channel; Erlang ব্যবহার করে message passing (shared memory নেই)।
8. Multi-language MCQ Corner8. Multi-language MCQ Corner
Ten tiny "what is the output?" snippets. Try each one yourself before reading the answer. Every output below was checked by actually running the code (Python 3, Java 17+, GCC on 64-bit Linux).
দশটা ছোট "output কী হবে?" snippet। Answer পড়ার আগে নিজে চেষ্টা করো। নিচের প্রতিটা output আসলে code চালিয়ে check করা হয়েছে (Python 3, Java 17+, 64-bit Linux-এ GCC)।
PythonPython
print(7 // 2, -7 // 2, 7 / 2, -7 % 3)
3 -4 3.5 2// is floor division: it rounds down toward −∞, so −3.5 becomes −4 (C and Java give −3, because they round toward 0). / is always true division in Python 3 → float 3.5. The % result takes the sign of the divisor: -7 = 3 × (-3) + 2, so -7 % 3 = 2 (C/Java give −1).3 -4 3.5 2// হলো floor division: এটা −∞-এর দিকে নিচে round করে, তাই −3.5 হয় −4 (C আর Java দেয় −3, কারণ তারা 0-এর দিকে round করে)। Python 3-এ / সবসময় true division → float 3.5। %-এর result divisor-এর sign নেয়: -7 = 3 × (-3) + 2, তাই -7 % 3 = 2 (C/Java দেয় −1)।a = [10, 20, 30, 40, 50]
print(a[1:4], a[::-2], a[-2:])
[20, 30, 40] [50, 30, 10] [40, 50]a[start:stop] includes start but excludes stop → indexes 1, 2, 3. a[::-2] starts at the end and takes every 2nd item backward. a[-2:] = last two items.[20, 30, 40] [50, 30, 10] [40, 50]a[start:stop]-এ start থাকে কিন্তু stop থাকে না → index 1, 2, 3। a[::-2] শেষ থেকে শুরু করে পেছনের দিকে প্রতি ২য় item নেয়। a[-2:] = শেষ দুইটা item।def add(x, lst=[]):
lst.append(x)
return lst
print(add(1))
print(add(2))
print(add(3, []))
[1][1, 2][3]The default value
[] is created once, when the def runs (binding at function-definition time), not on every call. So calls without lst share the same list. The third call passes its own new list. Fix: def add(x, lst=None): if lst is None: lst = [].[1][1, 2][3]Default value
[] তৈরি হয় একবারই, যখন def চলে (function-definition time-এ binding), প্রতি call-এ না। তাই lst ছাড়া করা call-গুলো একই list share করে। তৃতীয় call নিজের নতুন list পাঠায়। Fix: def add(x, lst=None): if lst is None: lst = []।is vs ==is vs ==a = [1, 2]; b = [1, 2]; c = a
print(a == b, a is b, a is c)
True False True== compares values (same content). is compares identity (same object in memory). a and b are two different lists with equal content. c = a makes an alias, not a copy. (Same idea as Java's == vs .equals() — see Chapter 02 Java Corner.)True False True== value তুলনা করে (content একই কি না)। is identity তুলনা করে (memory-তে একই object কি না)। a আর b একই content-এর দুটো আলাদা list। c = a একটা alias বানায়, copy না। (Java-র == vs .equals()-এর মতোই idea — Chapter 02 Java Corner দেখো।)JavaJava
int x = Integer.MAX_VALUE; // 2147483647
x = x + 1;
System.out.println(x);
-2147483648Java
int is 32-bit two's complement. Going past the maximum wraps around to the minimum. Java does not throw an exception for integer overflow. (In C, signed overflow is undefined behaviour. In Python, integers never overflow — they grow as big as needed.)-2147483648Java-র
int 32-bit two's complement। Maximum পার হলে ঘুরে minimum-এ চলে যায়। Integer overflow-এর জন্য Java কোনো exception দেয় না। (C-তে signed overflow undefined behaviour। Python-এ integer কখনো overflow হয় না — যত বড় দরকার তত বড় হয়।)char c = 'A';
System.out.println(c + 1);
System.out.println((char)(c + 1));
System.out.println("" + c + 1);
66BA1Line 1:
char + int → the char is promoted to int ('A' = 65), so 66. Line 2: cast back to char → 'B'. Line 3: evaluation is left to right; "" + c is the String "A", then "A" + 1 is string concatenation → "A1".66BA1Line 1:
char + int → char promote হয়ে int হয় ('A' = 65), তাই 66। Line 2: আবার char-এ cast → 'B'। Line 3: evaluation বাম থেকে ডানে; "" + c হলো String "A", তারপর "A" + 1 string concatenation → "A1"।+ order+-এর orderString s = "hi";
s.concat(" there");
System.out.println(s);
s = s.concat(" there");
System.out.println(s);
System.out.println(1 + 2 + "3" + 4 + 5);
hihi there3345Java
String is immutable: concat returns a new String; if you ignore the result, s does not change. For the last line, + is left-associative: 1 + 2 = 3 (both ints), then 3 + "3" = "33" (now a String), then "334", then "3345". (More on the String pool in Chapter 02.)hihi there3345Java-র
String immutable: concat একটা নতুন String return করে; result ফেলে দিলে s বদলায় না। শেষ line-এ + left-associative: 1 + 2 = 3 (দুটোই int), তারপর 3 + "3" = "33" (এখন String), তারপর "334", তারপর "3345"। (String pool নিয়ে আরও আছে Chapter 02-এ।)CC
sizeof vs strlensizeof vs strlenchar s[] = "BUET";
char *p = "BUET";
printf("%zu %zu %zu\n", sizeof(s), strlen(s), sizeof(p));
5 4 8sizeof(s) counts the array bytes including the hidden '\0' → 5. strlen counts characters before '\0' → 4. sizeof(p) is the size of a pointer, not the string → 8 on a 64-bit machine (4 on 32-bit). sizeof is worked out at compile time.5 4 8sizeof(s) লুকানো '\0' সহ array-র byte গোনে → 5। strlen '\0'-এর আগের character গোনে → 4। sizeof(p) হলো একটা pointer-এর size, string-এর না → 64-bit machine-এ 8 (32-bit-এ 4)। sizeof compile time-এ হিসাব হয়।int i = 5;
int j = i++ + 10;
int k = ++i * 2;
printf("%d %d %d\n", i, j, k);
7 15 14i++ gives the old value 5, then i becomes 6 → j = 5 + 10 = 15. ++i makes i = 7 first, then uses 7 → k = 14. (Each statement changes i only once, so this is well-defined. Something like i++ + ++i would be undefined behaviour.)7 15 14i++ পুরোনো value 5 দেয়, তারপর i হয় 6 → j = 5 + 10 = 15। ++i আগে i = 7 করে, তারপর 7 ব্যবহার করে → k = 14। (প্রতিটা statement i-কে একবারই বদলায়, তাই এটা well-defined। i++ + ++i-এর মতো কিছু হলে undefined behaviour।)int a = 7, b = 2;
float f = a / b;
printf("%.2f %.2f %d %d\n", f, (float)a / b, -7 / 2, -7 % 3);
3.00 3.50 -3 -1a / b is int / int, so the answer is 3 first; only then is it converted to float 3.00. Cast one operand first ((float)a / b) to get 3.50. C (since C99) truncates toward zero: -7 / 2 = -3, and -7 % 3 = -1 (sign follows the dividend). Compare with Python's -4 and 2 in Snippet 1!3.00 3.50 -3 -1a / b হলো int / int, তাই আগে answer হয় 3; তারপরে float 3.00-এ convert হয়। 3.50 পেতে আগে একটা operand cast করো ((float)a / b)। C (C99 থেকে) শূন্যের দিকে truncate করে: -7 / 2 = -3, আর -7 % 3 = -1 (sign dividend-এর মতো)। Snippet 1-এর Python-এর -4 আর 2-এর সাথে তুলনা করো!-7 / 2 → C/Java: −3, Python //: −4, Python /: −3.5. -7 % 3 → C/Java: −1, Python: 2. Integer overflow → C: undefined, Java: wraps, Python: never. a > b > c → C/JS: left-assoc trick, Java: compile error, Python: chained comparison.-7 / 2 → C/Java: −3, Python //: −4, Python /: −3.5। -7 % 3 → C/Java: −1, Python: 2। Integer overflow → C: undefined, Java: wrap হয়, Python: কখনো না। a > b > c → C/JS: left-assoc trick, Java: compile error, Python: chained comparison।Practice Questions (IICT Style)Practice Questions (IICT Style)
20 questions, easy → hard. Q1–Q12 are IICT MCQ style; Q13–Q20 are IICT written style (trace / explain). Every code output was verified by running it.
২০টা প্রশ্ন, সহজ → কঠিন। Q1–Q12 IICT MCQ style; Q13–Q20 IICT written style (trace / ব্যাখ্যা)। প্রতিটা code output চালিয়ে verify করা।
Show Answerউত্তর দেখুন
Show Answerউত্তর দেখুন
Show Answerউত্তর দেখুন
javac makes platform-independent .class bytecode; the JVM runs it, and its JIT compiler turns hot code into machine code at run time. This gives "write once, run anywhere".javac platform-independent .class bytecode বানায়; JVM সেটা চালায়, আর তার JIT compiler run time-এ hot code-কে machine code বানায়। এজন্যই "write once, run anywhere"।Show Answerউত্তর দেখুন
x = 5 then x = "hi" is fine). Strong: Python refuses to silently mix unrelated types — "5" + 3 raises TypeError. JavaScript would be dynamic and weak ("5" + 3 gives "53").x = 5 তারপর x = "hi" — কোনো সমস্যা নেই)। Strong: Python চুপচাপ সম্পর্কহীন type মেশায় না — "5" + 3 দিলে TypeError। JavaScript হলো dynamic আর weak ("5" + 3 দেয় "53")।Show Answerউত্তর দেখুন
static/global variable's cell at load time — those are the distractors.static/global variable-এর cell load time-এ — ওগুলো হলো ভুল option-এর ফাঁদ।print(2 ** 3 ** 2)
print(2 ** 3 ** 2)
Show Answerউত্তর দেখুন
** is right-associative: 2 ** (3 ** 2) = 2 ** 9 = 512. If you wrongly go left to right you get (2 ** 3) ** 2 = 64, which is the trap option.** right-associative: 2 ** (3 ** 2) = 2 ** 9 = 512। ভুল করে বাম থেকে ডানে করলে পাবে (2 ** 3) ** 2 = 64, যেটা trap option।int a = 0, b = 5;
if (a && ++b) {}
if (a || ++b) {}
printf("%d %d", a, b);
int a = 0, b = 5;
if (a && ++b) {}
if (a || ++b) {}
printf("%d %d", a, b);
Show Answerউত্তর দেখুন
if: a is 0 (false), so && skips ++b. Second if: a is false, so || must check the right side → ++b runs, b = 6. a is never changed. Output 0 6 (verified).if: a 0 (false), তাই && ++b skip করে। দ্বিতীয় if: a false, তাই ||-কে ডান পাশ দেখতেই হবে → ++b চলে, b = 6। a কখনো বদলায় না। Output 0 6 (verified)।int x = 1;
void p() { print(x); }
void q() { int x = 2; p(); }
main() { q(); }
int x = 1;
void p() { print(x); }
void q() { int x = 2; p(); }
main() { q(); }
Show Answerউত্তর দেখুন
x is non-local in p. Static: p is written at the top level, so its x is the global x = 1. Dynamic: look at the caller of p, which is q; q has x = 2, so it prints 2. (Checked in Bash, which is dynamically scoped: prints 2.)p-তে x non-local। Static: p top level-এ লেখা, তাই তার x হলো global x = 1। Dynamic: p-এর caller q-তে দেখো; q-তে x = 2, তাই print হয় 2। (Bash-এ check করা, যেটা dynamically scoped: 2 print করে।)Show Answerউত্তর দেখুন
System.out.println('a' + 'b' + "c");
System.out.println('a' + 'b' + "c");
Show Answerউত্তর দেখুন
+ goes left to right. 'a' + 'b' is char + char, which is numeric addition after promotion to int: 97 + 98 = 195. Then 195 + "c" is String concatenation → "195c" (verified).+ বাম থেকে ডানে চলে। 'a' + 'b' হলো char + char, যা int-এ promote হয়ে সংখ্যার যোগ: 97 + 98 = 195। তারপর 195 + "c" String concatenation → "195c" (verified)।new belongs to which lifetime category?
new দিয়ে তৈরি Java object কোন lifetime category-র?
Show Answerউত্তর দেখুন
new operator. (Java frees it implicitly via garbage collection, but allocation is explicit.) Implicit heap-dynamic means storage is bound just by assigning, like Python/JavaScript variables.new operator দিয়ে explicitly heap memory চায়। (Java garbage collection দিয়ে implicitly free করে, কিন্তু allocation explicit।) Implicit heap-dynamic মানে শুধু assign করলেই storage bind হয়, যেমন Python/JavaScript variable।x = [[0] * 2] * 2
x[0][0] = 1
print(x)
x = [[0] * 2] * 2
x[0][0] = 1
print(x)
Show Answerউত্তর দেখুন
[inner] * 2 copies the reference to the same inner list twice, so x[0] and x[1] are aliases of one list. Changing x[0][0] shows up in both rows. Correct way: x = [[0] * 2 for _ in range(2)] (verified).[inner] * 2 একই inner list-এর reference দুবার copy করে, তাই x[0] আর x[1] একটা list-এরই alias। x[0][0] বদলালে দুই row-তেই দেখা যায়। ঠিক উপায়: x = [[0] * 2 for _ in range(2)] (verified)।Show Answerউত্তর দেখুন
- Compiler: translates the whole program into machine code once; the executable then runs fast; errors reported before running; output depends on the target CPU/OS (C, C++).
- Interpreter: reads and runs the source one statement at a time; no executable; slow (each statement is decoded every time it runs); easy to debug (Bash, early BASIC).
- Hybrid: compile to an intermediate bytecode, then a virtual machine interprets it (Java, Python, C#). Faster than pure interpretation, and portable.
javac produces bytecode, not machine code. Bytecode is the same on every OS. Any machine with a JVM can run it → "write once, run anywhere". Only the JVM itself is platform-specific.JIT: a compiler inside the JVM that, at run time, compiles frequently used ("hot") bytecode into native machine code and caches it. Later calls run native code directly, so the cost of interpreting is removed from loops and hot methods. It can even optimize using real run-time information.
- Compiler: পুরো program একবারে machine code-এ translate করে; তারপর executable দ্রুত চলে; চালানোর আগেই error জানায়; output target CPU/OS-এর ওপর নির্ভরশীল (C, C++)।
- Interpreter: source একবারে একটা statement পড়ে আর চালায়; executable নেই; ধীর (প্রতিটা statement যতবার চলে ততবার decode হয়); debug করা সহজ (Bash, পুরোনো BASIC)।
- Hybrid: intermediate bytecode-এ compile, তারপর virtual machine সেটা interpret করে (Java, Python, C#)। Pure interpretation-এর চেয়ে দ্রুত, আর portable।
javac machine code না, bytecode বানায়। Bytecode সব OS-এ একই। JVM আছে এমন যেকোনো machine এটা চালাতে পারে → "write once, run anywhere"। শুধু JVM নিজে platform-specific।JIT: JVM-এর ভেতরের একটা compiler, যা run time-এ বারবার ব্যবহৃত ("hot") bytecode-কে native machine code-এ compile করে cache করে রাখে। পরের call-গুলো সরাসরি native code চালায়, তাই loop আর hot method থেকে interpret করার খরচ চলে যায়। এটা আসল run-time তথ্য দেখে optimize-ও করতে পারে।
"5" + 3 and "5" - 3 in JavaScript and "5" + 3 in Python, and say what each shows."5" + 3 আর "5" - 3, আর Python-এ "5" + 3-এর result লেখো, আর প্রতিটা কী বোঝায় বলো।Show Answerউত্তর দেখুন
- C: static, weak (unions, pointer casts, no bound check).
- Java: static, strong.
- Python: dynamic, strong.
- JavaScript: dynamic, weak.
"5" + 3 → "53" (number coerced to string, then concatenation); "5" - 3 → 2 (string coerced to number). Same-looking operations give different kinds of result — silent coercion = weak typing.Python:
"5" + 3 → TypeError at run time. The error is caught (strong), but only when the line runs (dynamic). You must convert explicitly: int("5") + 3 = 8. (All verified with Node.js and Python 3.)- C: static, weak (union, pointer cast, bound check নেই)।
- Java: static, strong।
- Python: dynamic, strong।
- JavaScript: dynamic, weak।
"5" + 3 → "53" (number string-এ coerce হয়ে concatenation); "5" - 3 → 2 (string number-এ coerce)। দেখতে একই রকম operation আলাদা ধরনের result দেয় — চুপচাপ coercion = weak typing।Python:
"5" + 3 → run time-এ TypeError। Error ধরা পড়ে (strong), কিন্তু শুধু line চলার সময় (dynamic)। Explicitly convert করতে হয়: int("5") + 3 = 8। (সব Node.js আর Python 3 দিয়ে verified।)int fib(int n) { if (n < 2) return n; return fib(n-1) + fib(n-2); } called as fib(3) from main: (i) How many times is fib called in total? (ii) What is the maximum number of activation records on the stack at one time (count main)? (iii) List what one activation record of fib contains.int fib(int n) { if (n < 2) return n; return fib(n-1) + fib(n-2); }-কে main থেকে fib(3) হিসেবে call করা হলো: (i) মোট কতবার fib call হয়? (ii) একসাথে stack-এ সর্বোচ্চ কয়টা activation record থাকে (main সহ)? (iii) fib-এর একটা activation record-এ কী কী থাকে লেখো।Show Answerউত্তর দেখুন
fib(3) → fib(2) + fib(1); fib(2) → fib(1) + fib(0).
- Calls: fib(3), fib(2), fib(1), fib(0), fib(1) = 5 calls. Result = 2.
- Deepest path: main → fib(3) → fib(2) → fib(1) (or fib(0)). That is 4 ARs (3 for fib + 1 for main). Note: the second
fib(1)(called from fib(3)) is pushed only after fib(2) has been popped, so the stack never holds all 5 fib calls at once. Depth grows as O(n) while total calls grow exponentially. - An AR of
fibholds: parametern; return address (inside the caller's expression); dynamic link (caller's AR / saved frame pointer); a temporary to hold the result offib(n-1)whilefib(n-2)runs; space for the return value (or a register). No static link is needed in C (no nested functions).
fib(3) → fib(2) + fib(1); fib(2) → fib(1) + fib(0)।
- Call: fib(3), fib(2), fib(1), fib(0), fib(1) = ৫টা call। Result = 2।
- সবচেয়ে গভীর path: main → fib(3) → fib(2) → fib(1) (বা fib(0))। মোট ৪টা AR (fib-এর ৩টা + main-এর ১টা)। খেয়াল করো: দ্বিতীয়
fib(1)(fib(3) থেকে call) push হয় শুধু fib(2) pop হওয়ার পরে, তাই stack-এ কখনো ৫টা fib call একসাথে থাকে না। Depth বাড়ে O(n) হারে, কিন্তু মোট call বাড়ে exponential হারে। fib-এর একটা AR-এ থাকে: parametern; return address (caller-এর expression-এর ভেতরে); dynamic link (caller-এর AR / saved frame pointer);fib(n-2)চলার সময়fib(n-1)-এর result রাখার একটা temporary; return value-এর জায়গা (বা register)। C-তে static link লাগে না (nested function নেই)।
int a = 1, b = 2;
void g() { a = a + b; print(a, b); }
void f() { int a = 10; b = b + 1; g(); print(a, b); }
main() { f(); print(a, b); }
int a = 1, b = 2;
void g() { a = a + b; print(a, b); }
void f() { int a = 10; b = b + 1; g(); print(a, b); }
main() { f(); print(a, b); }
Show Answerউত্তর দেখুন
f has a local a. Nobody has a local b, so b is always the global b in both rules.(a) Static scoping —
g is written at top level, so its a is the global a.
f: local a = 10; global b = 2 + 1 = 3.g: global a = 1 + 3 = 4 → prints 4 3.- Back in
f: its local a = 10, b = 3 → prints 10 3. main: global a = 4, b = 3 → prints 4 3.
g's a is found in its caller f.
f: local a = 10; b (global) = 3.g: f's a = 10 + 3 = 13 → prints 13 3.- Back in
f: its a is now 13 → prints 13 3. main: f is gone; global a was never changed = 1, b = 3 → prints 1 3.
4 3 / 10 3 / 4 3; the same program in Bash (dynamic scoping, local a=10) gives 13 3 / 13 3 / 1 3.f-এর local a আছে। কারও local b নেই, তাই দুই rule-এই b সবসময় global b।(a) Static scoping —
g top level-এ লেখা, তাই তার a global a।
f: local a = 10; global b = 2 + 1 = 3।g: global a = 1 + 3 = 4 → print 4 3।f-এ ফিরে: তার local a = 10, b = 3 → print 10 3।main: global a = 4, b = 3 → print 4 3।
g-এর a পাওয়া যায় তার caller f-এ।
f: local a = 10; b (global) = 3।g: f-এর a = 10 + 3 = 13 → print 13 3।f-এ ফিরে: তার a এখন 13 → print 13 3।main: f শেষ; global a কখনো বদলায়নি = 1, b = 3 → print 1 3।
4 3 / 10 3 / 4 3; একই program Bash-এ (dynamic scoping, local a=10) দেয় 13 3 / 13 3 / 1 3।a printed by main if parameters are passed (i) by value, (ii) by reference, (iii) by value-result (copy back x first, then y). Explain why (ii) and (iii) differ.
void f(int x, int y) { x = x + 1; y = y * 2; }
main() { int a = 3; f(a, a); print(a); }
x, তারপর y copy back) pass হয়, তাহলে main a-এর কোন value print করবে? (ii) আর (iii) কেন আলাদা, ব্যাখ্যা করো।
void f(int x, int y) { x = x + 1; y = y * 2; }
main() { int a = 3; f(a, a); print(a); }
Show Answerউত্তর দেখুন
- By value: x = 3, y = 3 are copies. Changes stay local.
a= 3. - By reference: x and y are both aliases of
a.x = x + 1→ a = 4.y = y * 2→ a = 4 × 2 = 8. - By value-result: copy in: x = 3, y = 3 (separate locals). x = 4, y = 6. Copy out: a = x = 4, then a = y = 6 → 6. (If the copy-back order were y then x, the answer would be 4 — so value-result with aliasing depends on the copy-back order.)
y still starts from 3. Verified with C++ references (8), value (3), and a copy-in/copy-out simulation (6).- By value: x = 3, y = 3 — copy। পরিবর্তন local-এই থাকে।
a= 3। - By reference: x আর y দুটোই
a-এর alias।x = x + 1→ a = 4।y = y * 2→ a = 4 × 2 = 8। - By value-result: copy in: x = 3, y = 3 (আলাদা local)। x = 4, y = 6। Copy out: a = x = 4, তারপর a = y = 6 → 6। (Copy-back order যদি আগে y পরে x হতো, উত্তর হতো 4 — তাই aliasing থাকলে value-result copy-back order-এর ওপর নির্ভর করে।)
y তখনো 3 থেকে শুরু করে। C++ reference (8), value (3), আর copy-in/copy-out simulation (6) দিয়ে verified।swap(i, a[i]) with i = 1 and a[1] = 3, a[2] = 5, a[3] = 7. Find i and the array after the call using (a) pass-by-reference and (b) pass-by-name. Does swap work in both?
procedure swap(x, y) {
t = x;
x = y;
y = t;
}
i = 1 আর a[1] = 3, a[2] = 5, a[3] = 7 অবস্থায় swap(i, a[i]) হিসেবে call করা হলো। (a) pass-by-reference আর (b) pass-by-name-এ call-এর পরে i আর array কী হবে? দুই ক্ষেত্রেই কি swap কাজ করে?
procedure swap(x, y) {
t = x;
x = y;
y = t;
}
Show Answerউত্তর দেখুন
(a) By reference: at the call, x →
i, y → a[1] (addresses fixed now, since i = 1).
t = i = 1; i = a[1] = 3; a[1] = t = 1. Result: i = 3, a = [1, 5, 7]. Correct swap ✓.(b) By name: x means the text
i, y means the text a[i], re-evaluated at each use.
t = i→ t = 1.i = a[i]→ i = a[1] = 3.a[i] = t→ now i is 3, so a[3] = 1.
a[1] was never changed, and a[3] was wrongly overwritten. Swap fails ✗. This famous example shows why it is impossible to write a correct general swap using pass-by-name in ALGOL 60. (Both results verified by simulation.)(a) By reference: call-এর সময় x →
i, y → a[1] (address এখনই ঠিক, কারণ i = 1)।
t = i = 1; i = a[1] = 3; a[1] = t = 1। Result: i = 3, a = [1, 5, 7]। ঠিকমতো swap ✓।(b) By name: x মানে text
i, y মানে text a[i], প্রতিবার ব্যবহারে আবার evaluate হয়।
t = i→ t = 1।i = a[i]→ i = a[1] = 3।a[i] = t→ এখন i = 3, তাই a[3] = 1।
a[1] কখনো বদলায়নি, আর a[3] ভুল করে overwrite হয়েছে। Swap ব্যর্থ ✗। এই বিখ্যাত example দেখায় কেন ALGOL 60-এ pass-by-name দিয়ে একটা সঠিক general swap লেখা অসম্ভব। (দুই result-ই simulation দিয়ে verified।)r that points to P. Pointers: P → Q, Q → P, R → S, S → R, T → Q. (i) Give the reference count of each object. (ii) Which objects does reference counting free? (iii) Which objects does mark-and-sweep free? (iv) Explain the difference.r, যেটা P-কে point করে। Pointer: P → Q, Q → P, R → S, S → R, T → Q। (i) প্রতিটা object-এর reference count লেখো। (ii) Reference counting কোন object free করবে? (iii) Mark-and-sweep কোনগুলো free করবে? (iv) পার্থক্য ব্যাখ্যা করো।Show Answerউত্তর দেখুন
- Counts: P = 2 (from r and Q), Q = 2 (from P and T), R = 1 (from S), S = 1 (from R), T = 0.
- Reference counting: only T has count 0 → T is freed. Freeing T removes the pointer T → Q, so Q drops to 1 (still alive, correctly). R and S keep count 1 forever → leaked. Freed: {T}.
- Mark-and-sweep: mark from root r → P → Q (→ P already marked). Marked = {P, Q}. Sweep the unmarked: {R, S, T}.
- Reference counting only knows "how many pointers", not "reachable from a root". The unreachable cycle R ⇄ S keeps its own counts above 0. Mark-and-sweep asks the right question (reachability from roots), so it frees cycles. Note the P ⇄ Q cycle is reachable, so both methods correctly keep it.
- Count: P = 2 (r আর Q থেকে), Q = 2 (P আর T থেকে), R = 1 (S থেকে), S = 1 (R থেকে), T = 0।
- Reference counting: শুধু T-এর count 0 → T free। T free হলে T → Q pointer চলে যায়, তাই Q-এর count হয় 1 (ঠিকভাবেই বেঁচে থাকে)। R আর S-এর count চিরকাল 1 → leak। Free হয়: {T}।
- Mark-and-sweep: root r থেকে mark → P → Q (→ P আগেই marked)। Marked = {P, Q}। Unmarked-গুলো sweep: {R, S, T}।
- Reference counting শুধু জানে "কয়টা pointer", জানে না "root থেকে পৌঁছানো যায় কি না"। Unreachable cycle R ⇄ S নিজেরাই নিজেদের count 0-এর ওপরে রাখে। Mark-and-sweep সঠিক প্রশ্ন করে (root থেকে reachability), তাই cycle free করে। খেয়াল করো, P ⇄ Q cycle reachable, তাই দুই method-ই সেটা ঠিকভাবে রেখে দেয়।
b(0) is changed to b(1). Explain exception propagation and the role of finally.
public class Ex {
static void c(int n) {
try {
System.out.println("c start");
if (n == 0) throw new ArithmeticException("zero");
System.out.println("c end");
} finally {
System.out.println("c finally");
}
}
static void b(int n) {
try { c(n); System.out.println("b after c"); }
catch (NullPointerException e) { System.out.println("b caught NPE"); }
}
public static void main(String[] args) {
try { b(0); System.out.println("main after b"); }
catch (ArithmeticException e) { System.out.println("main caught " + e.getMessage()); }
finally { System.out.println("main finally"); }
System.out.println("done");
}
}
b(0)-কে b(1) করলে output কী হবে লেখো। Exception propagation আর finally-এর ভূমিকা ব্যাখ্যা করো।
public class Ex {
static void c(int n) {
try {
System.out.println("c start");
if (n == 0) throw new ArithmeticException("zero");
System.out.println("c end");
} finally {
System.out.println("c finally");
}
}
static void b(int n) {
try { c(n); System.out.println("b after c"); }
catch (NullPointerException e) { System.out.println("b caught NPE"); }
}
public static void main(String[] args) {
try { b(0); System.out.println("main after b"); }
catch (ArithmeticException e) { System.out.println("main caught " + e.getMessage()); }
finally { System.out.println("main finally"); }
System.out.println("done");
}
}
Show Answerউত্তর দেখুন
b(0)):
c start
c finally
main caught zero
main finally
done
cprints "c start", then throwsArithmeticException. "c end" is skipped.chas no catch, but itsfinallyalways runs → "c finally". Then the exception propagates tob(c's AR is popped).bonly catchesNullPointerException— no match. "b after c" is skipped; the exception propagates tomain.main's catch matches → "main caught zero". "main after b" was skipped.main'sfinallyruns → "main finally". The exception is handled, so execution continues after the try statement → "done".
b(1) (no exception):
c start
c end
c finally
b after c
main after b
main finally
done
finally runs in both cases. Both outputs verified with javac/java.b(0) দিয়ে):
c start
c finally
main caught zero
main finally
done
c"c start" print করে, তারপরArithmeticExceptionthrow করে। "c end" skip হয়।c-তে catch নেই, কিন্তু তারfinallyসবসময় চলে → "c finally"। তারপর exceptionb-তে propagate করে (c-এর AR pop হয়)।bশুধুNullPointerExceptioncatch করে — মেলে না। "b after c" skip হয়; exceptionmain-এ propagate করে।main-এর catch মিলে যায় → "main caught zero"। "main after b" skip হয়েছিল।main-এরfinallyচলে → "main finally"। Exception handle হয়ে গেছে, তাই try statement-এর পরে execution চলতে থাকে → "done"।
b(1) দিয়ে (কোনো exception নেই):
c start
c end
c finally
b after c
main after b
main finally
done
দুই ক্ষেত্রেই finally চলে। দুটো output-ই javac/java দিয়ে verified।