CMP和JGE不能在Turbo c++中工作

CMP and JGE not working in Turbo C++

本文关键字:c++ 工作 Turbo JGE 不能 CMP      更新时间:2023-10-16

我正在用c++和汇编语言(8086)编写一个Mix程序,从数组中找到最小的数字。这是我的代码

#include<iostream>
#include<conio.h>
using namespace std;
void main()
{
__int16 a[5],x,y,res;
int i,j;
y=999;
cout<<"n Enter 5 Numbers:";
for(i=0;i<5;i++)
{
    cin>>a[i];
}
_asm{
    mov bx,y
}
//Finding smallest
for(i=0;i<5;i++)
{
    x=a[i];
    _asm{
        mov ax,x
        cmp ax,bx
        jge nxt
        mov bx,ax
        nxt:
    }
}
_asm{
    mov res,bx;
}
cout<<"n Smallest Element:"<<res;
getch();
}

上面的代码是在Visual Studio 2010中编写的,看起来工作得很好。但是当我为Turbo c++更新相同的代码时(即将"iostream"更改为"iostream.h",删除"使用命名空间std;",将"__int16"更改为"int"等),它不起作用。执行后产生的答案是错误的。

这是我的tc++程序相同的

#include<iostream.h>
#include<conio.h>
void main()
{
int a[5],x,y,res;
int i,j;
y=999;
cout<<"n Enter 5 Numbers:";
for(i=0;i<5;i++)
{
    cin>>a[i];
}
_asm{
    mov bx,y
}
//Finding smallest
for(i=0;i<5;i++)
{
    x=a[i];
    _asm{
        mov ax,x
        cmp ax,bx
        jge nxt
        mov bx,ax
    }
    nxt:
}
_asm{
    mov res,bx;
}
cout<<"n Smallest Element:"<<res;
getch();
}

为什么tc++和Visual Studio 10给出的答案不一样?

您不能期望寄存器在程序集片段之间保留它们的值。你有三个汇编片段,它们之间有C块,它们依赖于bx保持不变。编译器不做这样的承诺。

要么使用内存存储运行的最小值,要么使用单个程序集代码段重新定义。对于后一种方法,您必须在汇编中重写For循环和数组访问;这是可行的。这样的:

_asm{
mov dx, y ; we'll use dx instead of bx for the running minimum - long story
mov bx, a   ; that's the array pointer
mov si, 0 ; that's our i
loop:
    mov ax, [bx+si*2] ; read a[i] into ax; *2 because int is two bytes
    cmp ax,dx
    jge nxt
    mov dx, ax
    nxt:
    ;Now the for loop stuff
    inc si ; i++
    cmp si, 5 ; compare i to 5
    jl loop   ; if less, continue looping
; End of loop
mov res,dx;
}

我使用bx和si进行基+索引内存访问,因为在早期的x86 cpu上,您只能使用有限的寄存器子集(bx或bp为基,si或di为索引)进行这种内存访问。现在,你可以使用寄存器的任何组合;但我不确定古董Turbo C是否会接受。