Saturday, 22 March 2025

Connecting to Database Using MySQL

 5.3 Connecting to Database Using MySQL 

MySQL Connector/Python.
MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it does that using the Python Database API Specification v2.0 (PEP 249). It uses the Python standard library and has no dependencies.
 

Connecting to the Database

The mysql.connector provides the connect() method used to create a connection between the MySQL database and the Python application. The syntax is given below.

Syntax:

Conn_obj= mysql.connector.connect(host = <hostname>, user = <username>, passwd = <password>)   

The connect() function accepts the following arguments.

Hostname – It represents the server name or IP address on which MySQL is running.
Username – It represents the name of the user that we use to work with the MySQL server. By default, the username for the MySQL database is root.
Password – The password is provided at the time of installing the MySQL database. We don’t need to pass a password if we are using the root.
Database – It specifies the database name which we want to connect. This argument is used when we have multiple databases.
 

In the following example we will be connecting to MySQL database using connect()
Example:
 

  • Python3

# Python program to connect

# to mysql database

 

 

import mysql.connector

 

 

# Connecting from the server

conn = mysql.connector.connect(user = 'username',

                               host = 'localhost',

                              database = 'database_name')

 

print(conn)

 

# Disconnecting from the server

conn.close()

Output:
 

python-mysql-connect-1

Also for the same, we can use connection.MySQLConnection() class instead of connect():
Example:
 

  • Python3

# Python program to connect

# to mysql database

 

 

from mysql.connector import connection

 

# Connecting to the server

conn = connection.MySQLConnection(user = 'username',

                              host = 'localhost',

                              database = 'database_name')

 

print(conn)

 

# Disconnecting from the server

conn.close()

Output:
 

python-mysql-connect-2

Another way is to pass the dictionary in the connect() function using ‘**’ operator:
Example:
 

  • Python3

# Python program to connect

# to mysql database

 

 

from mysql.connector import connection

 

 

dict = {

  'user': 'root',

  'host': 'localhost',

  'database': 'College'

}

 

# Connecting to the server

conn = connection.MySQLConnection(**dict)

 

print(conn)

 

# Disconnecting from the server

conn.close()

Output:
 

python-mysql-connect-3

 Example

  • Python3

# importing required libraries

import mysql.connector

 

dataBase = mysql.connector.connect(

host ="localhost",

user ="user",

passwd ="gfg"

)

 

# preparing a cursor object

cursorObject = dataBase.cursor()

 

# creating database

cursorObject.execute("CREATE DATABASE geeks4geeks")

 


Wednesday, 19 March 2025

Creating GUI Using Tkinter

5.2  Creating GUI Using Tkinter

Creating a GUI Using Tkinter in Python

Tkinter is the standard Python library for creating Graphical User Interfaces (GUIs). It provides widgets like buttons, labels, text boxes, and more to build interactive applications.


1. Basic Tkinter Window

A simple Tkinter window can be created with just a few lines of code.


import tkinter as tk # Create the main application window root = tk.Tk() # Set window title root.title("My First Tkinter App") # Set window size root.geometry("400x300") # Run the Tkinter event loop root.mainloop()

Explanation:

  • tk.Tk() initializes the main window.
  • title("My First Tkinter App") sets the window title.
  • geometry("400x300") sets the window size.
  • mainloop() starts the GUI event loop.

2. Adding Widgets (Labels, Buttons, Entry)


import tkinter as tk root = tk.Tk() root.title("Simple GUI") root.geometry("400x300") # Create a Label label = tk.Label(root, text="Hello, Tkinter!", font=("Arial", 16)) label.pack(pady=10) # Add some padding # Create an Entry Field entry = tk.Entry(root, width=30) entry.pack(pady=10) # Function to handle button click def on_button_click(): user_text = entry.get() # Get text from entry label.config(text=f"Hello, {user_text}!") # Update label # Create a Button button = tk.Button(root, text="Click Me", command=on_button_click) button.pack(pady=10) root.mainloop()

Explanation:

  • Label displays text.
  • Entry allows text input.
  • Button executes a function when clicked.
  • pack() is used to arrange widgets.

3. Using Grid Layout

Instead of pack(), you can use grid() for better layout control.


import tkinter as tk root = tk.Tk() root.title("Grid Layout Example") # Create widgets tk.Label(root, text="Name:").grid(row=0, column=0, padx=10, pady=10) name_entry = tk.Entry(root) name_entry.grid(row=0, column=1, padx=10, pady=10) tk.Label(root, text="Age:").grid(row=1, column=0, padx=10, pady=10) age_entry = tk.Entry(root) age_entry.grid(row=1, column=1, padx=10, pady=10) # Button to print input values def submit(): print(f"Name: {name_entry.get()}, Age: {age_entry.get()}") tk.Button(root, text="Submit", command=submit).grid(row=2, column=0, columnspan=2, pady=10) root.mainloop()

Explanation:

  • grid(row, column) places widgets in a table-like structure.
  • columnspan=2 makes the button span two columns.

4. Message Box (Popup Dialogs)


import tkinter as tk from tkinter import messagebox def show_message(): messagebox.showinfo("Greeting", "Hello, Tkinter!") root = tk.Tk() root.title("Message Box Example") tk.Button(root, text="Show Message", command=show_message).pack(pady=20) root.mainloop()

Explanation:

  • messagebox.showinfo() creates a popup message.

5. File Dialog (Open/Save Files)


import tkinter as tk from tkinter import filedialog def open_file(): file_path = filedialog.askopenfilename() if file_path: print("Selected File:", file_path) root = tk.Tk() root.title("File Dialog Example") tk.Button(root, text="Open File", command=open_file).pack(pady=20) root.mainloop()

Explanation:

  • filedialog.askopenfilename() allows users to select a file.

6. Building a Simple Calculator


import tkinter as tk root = tk.Tk() root.title("Simple Calculator") entry = tk.Entry(root, width=30, borderwidth=5) entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10) # Function to handle button clicks def button_click(number): entry.insert(tk.END, number) def clear(): entry.delete(0, tk.END) def calculate(): try: result = eval(entry.get()) entry.delete(0, tk.END) entry.insert(tk.END, str(result)) except: entry.delete(0, tk.END) entry.insert(tk.END, "Error") # Button layout buttons = [ ('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3), ('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3), ('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3), ('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3) ] for text, row, col in buttons: tk.Button(root, text=text, width=5, height=2, command=lambda t=text: button_click(t) if t != '=' else calculate()).grid(row=row, column=col) tk.Button(root, text="C", width=5, height=2, command=clear).grid(row=4, column=3) root.mainloop()

Explanation:

  • Uses grid() to place buttons in a calculator layout.
  • eval() computes the mathematical expression entered by the user.
  • lambda allows passing values dynamically to functions.

7. Adding a Menu Bar


import tkinter as tk def open_file(): print("Open file clicked") root = tk.Tk() root.title("Menu Bar Example") menu_bar = tk.Menu(root) # File menu file_menu = tk.Menu(menu_bar, tearoff=0) file_menu.add_command(label="Open", command=open_file) file_menu.add_command(label="Exit", command=root.quit) menu_bar.add_cascade(label="File", menu=file_menu) root.config(menu=menu_bar) root.mainloop()

Explanation:

  • menu.add_command() adds menu items.
  • menu_bar.add_cascade() adds dropdown menus.

Summary

FeatureCode
Basic Windowtk.Tk()
LabelLabel(root, text="Hello")
ButtonButton(root, text="Click Me", command=function)
Entry (Text Box)Entry(root)
Grid Layoutwidget.grid(row=0, column=0)
Popup Messagemessagebox.showinfo("Title", "Message")
File Dialogfiledialog.askopenfilename()
Calculatoreval(entry.get())
Menu BarMenu(root)

Pandas

5.1 Pandas

Pandas is one of the most powerful and widely used libraries in Python for data manipulation and analysis. It provides easy-to-use data structures and functions to efficiently handle large datasets.

Why Use Pandas?

  • Efficient data handling with DataFrames and Series
  • Supports CSV, Excel, SQL, JSON, and many other file formats
  • Powerful data cleaning, manipulation, and transformation tools
  • Built-in statistical and analytical functions
  • Easy integration with NumPy, Matplotlib, and other libraries

Installing Pandas

If you don’t have Pandas installed, you can install it using:


pip install pandas

1. Importing Pandas


import pandas as pd

2. Creating DataFrames

A DataFrame is a table-like structure that consists of rows and columns.

a) Creating a DataFrame from a Dictionary


data = { 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['New York', 'Los Angeles', 'Chicago'] } df = pd.DataFrame(data) print(df)

Output:


Name Age City 0 Alice 25 New York 1 Bob 30 Los Angeles 2 Charlie 35 Chicago

b) Creating a DataFrame from a CSV File


df = pd.read_csv('data.csv') print(df.head()) # Display first 5 rows

3. Basic DataFrame Operations

a) Checking Data Information


print(df.info()) # Summary of the dataset print(df.describe()) # Statistical summary print(df.shape) # Rows and columns count

b) Selecting Columns


print(df['Name']) # Selecting a single column print(df[['Name', 'Age']]) # Selecting multiple columns

c) Selecting Rows


print(df.iloc[0]) # Selecting the first row print(df.loc[df['Age'] > 30]) # Filtering rows where Age > 30

4. Data Manipulation

a) Adding a New Column


df['Salary'] = [50000, 60000, 70000] print(df)

b) Updating Values


df.loc[df['Name'] == 'Alice', 'Age'] = 26

c) Dropping a Column


df.drop(columns=['Salary'], inplace=True)

d) Handling Missing Data


df.fillna(0, inplace=True) # Replace NaN values with 0 df.dropna(inplace=True) # Remove rows with NaN values

5. Grouping and Aggregation


df_grouped = df.groupby('City')['Age'].mean() print(df_grouped)

6. Merging and Joining DataFrames


df1 = pd.DataFrame({'ID': [1, 2], 'Name': ['Alice', 'Bob']}) df2 = pd.DataFrame({'ID': [1, 2], 'Salary': [50000, 60000]}) df_merged = pd.merge(df1, df2, on='ID') print(df_merged)

7. Exporting Data


df.to_csv('output.csv', index=False) # Save as CSV df.to_excel('output.xlsx', index=False) # Save as Excel

Conclusion

Pandas is an essential tool for data analysis and manipulation in Python. It simplifies handling and processing of structured data, making it a must-learn library for data science and machine learning.

Introduction to Built in Package in Python

 Python provides a vast collection of built-in packages (also known as standard libraries) that simplify coding and enhance functionality. These built-in packages help developers perform tasks without needing external dependencies, making Python a powerful and versatile programming language.

What Are Built-in Packages?

Built-in packages are pre-installed modules in Python that provide various functionalities, such as file handling, mathematical operations, system interactions, and web handling. You can import and use these modules without installing them separately.

Commonly Used Built-in Packages

Here are some of the most commonly used built-in packages in Python:

1. math - Mathematical Operations

The math module provides mathematical functions like square root, trigonometric functions, logarithms, and more.

import math

 

print(math.sqrt(25))  # Output: 5.0

print(math.pi)        # Output: 3.141592653589793

print(math.factorial(5))  # Output: 120

2. random - Generating Random Numbers

The random module is used for generating random numbers, selecting random elements, and shuffling sequences.

import random

 

print(random.randint(1, 10))  # Random number between 1 and 10

print(random.choice(["apple", "banana", "cherry"]))  # Random selection from a list

3. datetime - Working with Dates and Time

The datetime module provides functions to handle dates and time-related tasks.

import datetime

 

current_time = datetime.datetime.now()

print("Current Time:", current_time)

4. os - Interacting with the Operating System

The os module provides functionalities to interact with the operating system, such as file handling and directory management.

import os

 

print(os.getcwd())  # Get the current working directory

os.mkdir("new_folder")  # Create a new directory

5. sys - System-specific Functions

The sys module provides access to system-specific parameters and functions.

import sys

 

print(sys.version)  # Prints Python version

print(sys.platform)  # Prints the operating system platform

6. json - Handling JSON Data

The json module helps in encoding and decoding JSON data.

import json

 

data = {"name": "John", "age": 25}

json_data = json.dumps(data)

print(json_data)  # Convert dictionary to JSON string

7. re - Regular Expressions

The re module is used for pattern matching and working with regular expressions.

import re

text = "Hello, my number is 123-456-7890"

pattern = r"\d{3}-\d{3}-\d{4}"

match = re.search(pattern, text)

if match:

    print("Phone number found:", match.group())

8. collections - Advanced Data Structures

The collections module provides specialized container data types like Counter, defaultdict, and deque.

from collections import Counter

 

words = ["apple", "banana", "apple", "orange", "banana", "apple"]

word_count = Counter(words)

print(word_count)  # Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})

Conclusion

Python's built-in packages make programming easier by providing ready-to-use functionalities. By mastering these modules, you can simplify your code and focus more on problem-solving rather than implementing low-level functionalities.

 

Monday, 17 March 2025

Procedure and Macro in Assembly Language Program

Procedure and Macro in Assembly Language

In assembly language programming, procedures and macros are two techniques used to structure and reuse code. They help in modularizing the program, reducing redundancy, and improving readability. However, they work differently in execution.


1. Procedure in Assembly Language

A procedure (also called a subroutine or function) is a block of code that performs a specific task. It is defined once and can be called multiple times in the program.

Key Features of Procedures

  • Uses CALL and RET instructions.
  • Saves memory by reusing code.
  • Allows parameter passing via registers, stack, or memory.
  • Helps in modularizing the program.

Syntax of a Procedure

Procedure_Name PROC   ; Procedure declaration

    ; Procedure body (set of instructions)

    RET               ; Return to the caller

Procedure_Name ENDP   ; End of the procedure

Example of a Procedure

.MODEL SMALL

.STACK 100H

.DATA

    MSG DB "Hello, World!$"

.CODE

MAIN PROC

    MOV AX, @DATA

    MOV DS, AX

   

    CALL DISPLAY_MSG   ; Calling the procedure

    MOV AH, 4CH

    INT 21H           ; Exit program

MAIN ENDP

 

DISPLAY_MSG PROC

    MOV DX, OFFSET MSG

    MOV AH, 09H

    INT 21H

    RET               ; Return to caller

DISPLAY_MSG ENDP

END MAIN

Explanation:

  • The DISPLAY_MSG procedure prints "Hello, World!".
  • The CALL DISPLAY_MSG statement invokes the procedure.
  • The RET instruction returns control back to the main program.

Advantages and Disadvantages of Procedures in Assembly Language

Advantages of Procedures

  1. Code Reusability

    • Procedures allow you to write a block of code once and reuse it multiple times, reducing redundancy.
  2. Memory Efficiency

    • Since procedures are stored separately and called when needed, they help save memory compared to macros, which expand inline.
  3. Modular Programming

    • They help break large programs into smaller, manageable units, making the code more readable and easier to debug.
  4. Parameter Passing

    • Procedures can accept parameters via registers, memory, or the stack, making them flexible for different tasks.
  5. Easy Maintenance

    • If a bug is found in a procedure, fixing it in one place updates all calls to it, simplifying debugging and modifications.
  6. Stack-Based Execution

    • Since procedures use the stack to store return addresses and parameters, they allow recursion and structured programming.

Disadvantages of Procedures

  1. Execution Overhead

    • Every procedure call involves pushing/popping return addresses on the stack and jumping to another location in memory, which adds some execution time.
  2. More Instructions

    • Calling and returning from a procedure involves additional instructions (CALL, RET, PUSH, POP), which can slow down execution compared to inline macros.
  3. Complex Debugging

    • If a program has many procedures, debugging can be challenging since execution control jumps across different locations in memory.
  4. Extra Stack Usage

    • Each procedure call consumes stack space for storing return addresses and parameters, which can be problematic in memory-constrained systems.
  5. Not Suitable for Small Repetitive Tasks

    • If a simple task (like printing a character) is implemented as a procedure, the overhead of calling and returning may outweigh its benefits.

When to Use Procedures?

✔ When memory optimization is needed.
✔ When modularity and reusability are important.
✔ When writing large programs that require structured programming.

Near and Far Procedures in Assembly Language

In assembly language programming, procedures (subroutines) can be classified into Near Procedures and Far Procedures based on the memory addressing mode.


1. Near Procedure

A near procedure is a procedure that is located within the same code segment as the calling function. Since it resides in the same segment, only the offset address is required to call and return from the procedure.

Key Features:

  • The procedure is within the same code segment (CS).
  • Only the offset is pushed onto the stack when calling the procedure.
  • Faster execution due to fewer memory operations.
  • Uses CALL (near) and RET instructions.
  • Suitable for small programs or procedures that are called frequently.

Syntax:

Procedure_Name PROC NEAR

    ; Procedure body

    RET   ; Near return

Procedure_Name ENDP

Example of a Near Procedure

.MODEL SMALL

.STACK 100H

.DATA

    MSG DB "Near Procedure Example!$"

.CODE


MAIN PROC

    MOV AX, @DATA

    MOV DS, AX

   

    CALL PRINT_MSG   ; Calling a near procedure

    MOV AH, 4CH

    INT 21H

MAIN ENDP


PRINT_MSG PROC NEAR

    MOV DX, OFFSET MSG

    MOV AH, 09H

    INT 21H

    RET   ; Return within the same segment

PRINT_MSG ENDP


END MAIN

Explanation:

  • PRINT_MSG is a near procedure because it resides in the same segment as MAIN.
  • When CALL PRINT_MSG is executed, only the offset address is pushed onto the stack.
  • RET retrieves the offset from the stack and returns to the calling function.

2. Far Procedure

A far procedure is a procedure located in a different segment from the calling function. Since it resides in a different segment, both the segment and offset addresses must be stored on the stack.

Key Features:

  • The procedure is in a different code segment.
  • Both segment and offset addresses are pushed onto the stack.
  • Uses CALL FAR and RET FAR instructions.
  • Slightly slower than near procedures due to additional memory operations.
  • Useful in large programs with multiple code segments.

Syntax:

Procedure_Name PROC FAR

    ; Procedure body

    RET   ; Far return

Procedure_Name ENDP

Example of a Far Procedure

.MODEL SMALL

.STACK 100H

.DATA

    MSG DB "Far Procedure Example!$"

.CODE


MAIN PROC

    MOV AX, @DATA

    MOV DS, AX

   

    CALL FAR PTR PRINT_MSG   ; Calling a far procedure

    MOV AH, 4CH

    INT 21H

MAIN ENDP


; Assume this procedure is in another segment

PRINT_MSG PROC FAR

    MOV DX, OFFSET MSG

    MOV AH, 09H

    INT 21H

    RETF   ; Far return

PRINT_MSG ENDP

 

END MAIN

Explanation:

  • PRINT_MSG is a far procedure, meaning it is in a different code segment.
  • CALL FAR PTR PRINT_MSG is used to explicitly call a far procedure.
  • When calling the procedure, both the segment and offset are pushed onto the stack.
  • RETF is used to return, which pops both segment and offset from the stack.

Difference Between Near and Far Procedures

Feature

Near Procedure

Far Procedure

Memory Location

Same code segment

Different code segment

Stack Storage

Only offset address is pushed

Both segment and offset addresses are pushed

Speed

Faster (

Directives for Procedures in Assembly Language

In assembly language, directives are special instructions that provide guidance to the assembler on how to process the program. When working with procedures, we use certain directives to define, call, and manage procedures efficiently.


1. PROC Directive

The PROC directive is used to define a procedure. It indicates the beginning of a procedure and specifies whether it is NEAR or FAR.

Syntax:

Procedure_Name PROC [NEAR | FAR]

    ; Procedure body

    RET

Procedure_Name ENDP

Example:

PRINT_MSG PROC NEAR

    MOV DX, OFFSET MSG

    MOV AH, 09H

    INT 21H

    RET

PRINT_MSG ENDP

✔ NEAR: Procedure is in the same code segment.
✔ FAR: Procedure is in a different segment.


2. ENDP Directive

The ENDP directive marks the end of a procedure definition. It must match a corresponding PROC directive.

Example:

SUM PROC NEAR

    ; Procedure body

    RET

SUM ENDP


3. CALL Directive

The CALL instruction is used to invoke a procedure. It pushes the return address onto the stack and jumps to the procedure.

Types of CALL:

  • CALL Procedure_Name → Calls a near procedure (same segment).
  • CALL FAR PTR Procedure_Name → Calls a far procedure (different segment).

Example:

CALL PRINT_MSG  ; Calls the procedure


4. RET Directive

The RET instruction is used to return from a procedure.

  • For near procedures, it pops the offset address from the stack.
  • For far procedures, it pops both the segment and offset addresses from the stack.

Example:

RET   ; Return from a near procedure

RETF  ; Return from a far procedure


5. FAR PTR and NEAR PTR Directives

When calling a procedure, you may need to explicitly specify whether it is near or far.

Example:

CALL NEAR PTR SUM      ; Calls a near procedure

CALL FAR PTR DISPLAY   ; Calls a far procedure


6. PUBLIC and EXTRN Directives

These directives are used when working with procedures in separate files.

  • PUBLIC → Declares a procedure so it can be accessed from other files.
  • EXTRN → Declares an external procedure (defined in another file).

Example (File 1 - Procedure Definition):

PUBLIC PRINT_MSG   ; Make procedure accessible to other files

PRINT_MSG PROC FAR

    MOV DX, OFFSET MSG

    MOV AH, 09H

    INT 21H

    RETF

PRINT_MSG ENDP

Example (File 2 - Calling External Procedure):

EXTRN PRINT_MSG: FAR  ; Declare external procedure

 

CALL PRINT_MSG        ; Call procedure from another file


7. END Directive

The END directive marks the end of the program. It tells the assembler that no more instructions follow.

Example:

END MAIN


Summary Table:

Directive

Description

PROC

Defines a procedure (NEAR/FAR)

ENDP

Marks the end of a procedure

CALL

Calls a procedure

RET / RETF

Returns from a procedure (near/far)

FAR PTR / NEAR PTR

Specifies procedure type in calls

PUBLIC

Makes procedure accessible in other files

EXTRN

Declares an external procedure

END

Marks the end of the program

Parameter Passing in Procedure

In assembly language, parameter passing in procedures (subroutines) can be done using different methods, depending on the architecture and calling conventions. The main methods are:

1. Passing Parameters via Registers

  • The fastest method since registers are directly accessible.
  • Common in modern RISC architectures (e.g., ARM, x86-64).
  • Example (x86-32, NASM syntax):

    mov eax, 5 ; First parameter mov ebx, 10 ; Second parameter call my_proc

    my_proc: add eax, ebx ; Perform operation ret

2. Passing Parameters via the Stack

  • Common in C-style calling conventions.
  • Parameters are pushed onto the stack before calling the procedure.
  • Used in x86 (cdecl, stdcall, etc.).
  • Example:

    push 5 ; First parameter push 10 ; Second parameter call my_proc add esp, 8 ; Clean up the stack (2 * 4 bytes) my_proc: push ebp ; Preserve base pointer mov ebp, esp ; New stack frame mov eax, [ebp+8] ; First parameter mov ebx, [ebp+12] ; Second parameter add eax, ebx pop ebp ; Restore base pointer ret

3. Passing Parameters via Global Memory

  • Uses memory locations or global variables to store parameters.
  • Useful when passing large amounts of data.
  • Example:

    section .data param1 dd 5 param2 dd 10 section .text mov eax, [param1] mov ebx, [param2] call my_proc my_proc: add eax, ebx ret

4. Passing Parameters via Parameter Blocks (Structs in Memory)

  • Useful for passing multiple parameters in a structured way.
  • Example (using a stack-based parameter block):

    section .data paramBlock dd 5, 10 ; Store parameters in memory section .text mov esi, paramBlock ; Load address of parameter block call my_proc my_proc: mov eax, [esi] ; Load first parameter mov ebx, [esi+4] ; Load second parameter add eax, ebx ret 

Each method has trade-offs in terms of speed and memory usage, and the best choice depends on the specific assembly language and architecture being used. Let me know if you need examples for a specific processor (x86, ARM, etc.). 


2. Macro in Assembly Language

A macro is a sequence of instructions that is defined once and can be used multiple times in a program. Unlike procedures, macros are expanded inline at the place of invocation.

Key Features of Macros

  • No CALL or RET instructions.
  • Faster execution as code is inserted directly.
  • Increases program size due to inlining.
  • Does not use stack for parameter passing.

Syntax of a Macro

MACRO_NAME MACRO PARAMETERS

    ; Macro body (set of instructions)

ENDM

Example of a Macro

.MODEL SMALL

.STACK 100H

.DATA

    MSG DB "Hello, Macro!$"

.CODE

PRINT MACRO MESSAGE

    MOV DX, OFFSET MESSAGE

    MOV AH, 09H

    INT 21H

ENDM

 

MAIN PROC

    MOV AX, @DATA

    MOV DS, AX

 

    PRINT MSG    ; Using the macro

    MOV AH, 4CH

    INT 21H

MAIN ENDP

END MAIN

Explanation:

  • The PRINT macro is defined to print a string.
  • When PRINT MSG is called, the assembler replaces it with the macro body.

Differences Between Procedures and Macros

Feature

Procedure

Macro

Call Type

Uses CALL and RET

Expands inline (no CALL)

Memory Usage

Uses less memory (reusable)

Increases code size (expands every time)

Execution Speed

Slower due to call/return overhead

Faster due to inlining

Parameter Passing

Uses stack, registers, or memory

Uses direct substitution

Best For

Large and reusable code blocks

Small repetitive tasks


When to Use What?

  • Use procedures when you need to reuse code multiple times and optimize memory.
  • Use macros when you need fast execution and short repetitive code.

Different assemblers provide different directives for defining macros. Below are some common directives used in macros:


The MACRO directive is used in MASM (Microsoft Macro Assembler) and TASM (Turbo Assembler) to define a reusable block of code, similar to a function but expanded inline at assembly time.


Syntax

macro_name MACRO [parameter1, parameter2, ...] ; Macro body (set of instructions) ENDM
  • macro_name → Name of the macro.
  • MACRO → Defines the start of the macro.
  • ENDM → Marks the end of the macro.

Example 1: Simple Macro (No Parameters)


DISPLAY_HELLO MACRO mov dx, OFFSET message ; Load message address mov ah, 09h ; DOS print string function int 21h ; Call DOS interrupt ENDM .DATA message db "Hello, Assembly!", "$" .CODE DISPLAY_HELLO ; Macro call (expands inline)
  • The macro DISPLAY_HELLO prints a message.
  • ENDM marks the end of the macro definition.
  • When called, the macro expands inline, replacing DISPLAY_HELLO with its body.

Example 2: Macro with Parameters


ADD_NUMS MACRO num1, num2 mov ax, num1 add ax, num2 ENDM .CODE ADD_NUMS 5, 10 ; Expands to `mov ax, 5` and `add ax, 10`
  • The macro takes two parameters and adds them.
  • During assembly, ADD_NUMS 5, 10 expands into:

    mov ax, 5 add ax, 10

Example 3: Macro with Multiple Instructions

PRINT_MSG MACRO msg mov dx, OFFSET msg mov ah, 09h int 21h ENDM .DATA msg1 db "Hello, World!$", 0 msg2 db "Assembly is fun!$", 0 .CODE PRINT_MSG msg1 PRINT_MSG msg2
  • The macro is used twice to print different messages.
  • The inline expansion makes execution faster but increases code size.

ENDM
Directive in Assembly Language

The ENDM directive is used to mark the end of a macro definition in assembly language. It is commonly used in assemblers like MASM (Microsoft Macro Assembler) and TASM (Turbo Assembler).


Syntax

macro_name MACRO [parameters] ; Macro body ENDM

Key Differences Between Macros and Procedures

Feature

Macros

Procedures

Expansion

Inline

Call/Return

Speed

Faster (no call overhead)

Slower (due to stack operations)

Code Size

Larger (each call expands code)

Smaller (single copy in memory)

Parameter Passing

Through macro arguments

Via registers or stack

Macros are ideal for small, frequently used code snippets, while procedures are better for large reusable blocks.

 

Desktop Virtualisation

Desktop Virtualization ( DV ) Desktop Virtualization ( DV ) is a technique that creates an illusion of a desktop provided to the user. It d...