Constants - assembly language

Prahlad Godara ------ From DOOSEEP

Constants are also a type of variable that stores a memory or instruction location or a constant value. The EQU instruction is used to define constants in the nasm assembly language.

Constants in NASM assembly language

There are several directives provided by NASM that define constants. EQU instruction, %assign instruction, %define instruction etc. to define constants.

In particular we will discuss three instructions
  1. EQU
  2. %assign
  3. %define

EQU Directive

EQU Directive is used to define a constant.

Syntax of EQU

CONSTANT_NAME EQU expression

Example

TOTAL_STUDENTS equ 50

using a constant value

mov  ecx,  TOTAL_STUDENTS 
    cmp  eax,  TOTAL_STUDENTS

The operand of an EQU statement can be an expression - and can be written as such.

LENGTH equ 20
        WIDTH  equ 10
        AREA   equ length * width

The above code section will store and define Area as 200.


Example

The following example shows the use of the EQU Directive-


    SYS_EXIT  equ 1
    SYS_WRITE equ 4
    STDIN     equ 0
    STDOUT    equ 1
    section	 .text
       global _start    ;must be declared for using gcc
        
    _start:             ;tell linker entry point
       mov eax, SYS_WRITE         
       mov ebx, STDOUT         
       mov ecx, msg1         
       mov edx, len1 
       int 0x80                
        
       mov eax, SYS_WRITE         
       mov ebx, STDOUT         
       mov ecx, msg2         
       mov edx, len2 
       int 0x80 
        
       mov eax, SYS_WRITE         
       mov ebx, STDOUT         
       mov ecx, msg3         
       mov edx, len3 
       int 0x80
       
       mov eax,SYS_EXIT    ;system call number (sys_exit)
       int 0x80            ;call kernel
    
    section	 .data
    msg1 db	'Hello, programmers!',0xA,0xD 	
    len1 equ $ - msg1			
    
    msg2 db 'Welcome to the world of,', 0xA,0xD 
    len2 equ $ - msg2 
    
    msg3 db 'NASM assembly programming! '
    len3 equ $- msg3

above code result

 Hello, programmers!
    Welcome to the world of,
    NASM assembly programming!

%assign Directive

% The ASSIGN Directive can be used to define numeric constants like the EQU instruction. This directive allows redistribution. For example, you can define the constant total as −


syntax

%assign TOTAL 10

Later in the code, you can redefine it as -

%assign TOTAL 30

This command is case-sensitive.


The %define Directive

% The define directive allows both numeric and string constants to be defined. For example, you can define the constant PTR as -


Example

 %define PTR [EBP+4]

The above code replaces PTR with [EBP+4].

This directive also allows reallocation and is case-sensitive.


Tags- education, Constants - Assembly Language , assembly language, type of Assembly Program Variable , example program in assembly language