Recursion is a unique way of implementing a function and is commonly used in high-level programming languages. A recursive function typically calls itself within itself and returns only when the base case- a special condition- is met.
The time and space complexity of recursive functions may be greater than usual functions in some cases. However, recursive functions are typically much shorter in size.
In assembly language, we can implement recursive functions using procedures.
Multiple procedures can be defined in the text
segment. Unless the base case is met, the same procedure may be called repeatedly. Upon meeting the base case, we can return from the procedure or terminate the program using the exit
system call.
The program below recursively prints the digits of an array in reverse order. First, we store an array with six elements alongside its size in a variable in the data
segment. Subsequently, we use the print
and check
procedures to print array elements and check whether or not the base case has been met. If the base case is met, the exit
system call is called to terminate the program gracefully.
section .textglobal _start_start:call checkprint:mov edi, arr ;fetches pointer to arrayadd edi, [count] ;updates and stores the adress of the array element in edi that is to be printedmov ecx, [edi] ;gets element in the adress that needs to be printed from the arrayadd ecx, 48 ;converts number in array to charpush ecx ;pushes to stack as we require an addressmov ecx, esp ;obtains the address of the number converted to char and saves it in ecxmov edx, 1 ;message length, 1 byte stored in edxmov ebx, 1 ;file descriptor number for stdout stream stored in ebxmov eax, 4 ;system call number for the write system call stored in eaxint 0x80 ;kernel interrupt to execute the write system call in kernel modedec byte [count] ;decrements countcall check ;calls checkretcheck:cmp byte [count], -1jg printmov eax, 1 ;system call number of the exit system callint 0x80 ;kernel interrupt to call the exit system callsection .dataarr db 1,2,3,4,5,6count db 5section .bss
Upon execution, the program prints the following output:
654321
Free Resources