#include <stdio.h>#include <stdlib.h>extern"C"int CompareArrays(int* y, constint* x, int n);
int main(int argc, char* argv[])
{
constint n = 21;
int x[n], y[n];
longint result;
// Initialize test arrays
srand(11);
for (int i = 0; i < n; i++)
x[i] = y[i] = rand() % 1000;
printf("\nResults for CompareArrays\n");
// Test using invalid 'n'
result = CompareArrays(x, y, -n);
printf(" Test #1 - expected: %3d actual: %3ld\n", -1, result);
// Test using first element mismatch
x[0] += 1;
result = CompareArrays(x, y, n);
x[0] -= 1;
printf(" Test #2 - expected: %3d actual: %3ld\n", 0, result);
// Test using middle element mismatch
y[n / 2] -= 2;
result = CompareArrays(x, y, n);
y[n / 2] += 2;
printf(" Test #3 - expected: %3d actual: %3ld\n", n / 2, result);
// Test using last element mismatch
x[n - 1] *= 3;
result = CompareArrays(x, y, n);
x[n - 1] /= 3;
printf(" Test #4 - expected: %3d actual: %3ld\n", n - 1, result);
// Test with identical elements in each array
result = CompareArrays(x, y, n);
printf(" Test #5 - expected: %3d actual: %3ld\n", n, result);
return0;
}
comparearrays.asm
; Name: comparearrays.asm;; Build: g++ -m32 -c main.cpp -o main.o; nasm -f elf32 -o comparearrays.o comparearrays.asm; g++ -m32 -o comparearrays comparearrays.o main.o;; Source: Modern x86 Assembly Language Programming p.81global CompareArrays
section .text
; extern "C" int CompareArrays(int* y, const int* x, int n);;; Description: This function compares two integer arrays element; by element for equality;; Returns: -1 Value of 'n' is invalid; 0 <= i < n Index of first non-matching element; n All elements match%define y [ebp+8]%define x [ebp+12]%define n [ebp+16]CompareArrays:pushebpmovebp,esppushesipushedi; Load arguments and validate 'n'moveax,-1;invalid 'n' return codemovesi,x ;esi = 'x'movedi,y ;edi = 'y'movecx,n ;ecx = 'n'testecx,ecxjle .l1 ;jump if 'n' <= 0moveax,ecx;eax = 'n; Compare the arrays for equalityrepecmpsdje .l1 ;arrays are equal; Calculate index of unequal elementssubeax,ecxdeceax;eax = index of mismatch.l1:popedipopesipopebpret