HLA递增检查程序为何恒输出false?附寄存器规则疑问
问题分析与修复方案
一、程序始终输出不递增的原因
你的程序核心问题是调用increasing过程时没有传递参数,导致过程内部读取的参数都是内存中的随机垃圾值,无论输入什么合法递增数值,判断逻辑都无法正确执行。
另外还有一个拼写小错误:过程参数里的valuel是字母L,而静态变量是value1(数字1),不过这不是当前问题的关键,核心还是参数传递缺失。
修复步骤:
- 调用过程时需要按约定传递参数,HLA中对于带参数的过程,需将参数从右往左压入栈中,修改主程序的调用代码:
// 按顺序压入参数(从右到左) push( value3 ); push( value2 ); push( value1 ); call increasing; // 调用后清理栈上的3个int8参数(共3字节) add( 3, ESP );
- 修正过程内的参数拼写错误,将
valuel改为value1(与静态变量名一致,避免混淆):
procedure increasing( value1 : int8; value2 : int8; value3 : int8 ); @nodisplay; @noframe;
二、关于寄存器约定的解释
“返回调用者后,你的函数除DX外不得修改任何其他寄存器的值”是x86汇编的调用约定规则,具体含义:
- 你的过程可以自由修改
DX寄存器的值,无需恢复其初始状态; - 对于其他通用寄存器(如AX、BX、CX、SI、DI等),过程执行时若需使用,必须先将原值保存到栈中,执行完逻辑后再从栈中恢复,确保返回调用者时这些寄存器的状态与调用前完全一致,避免破坏调用者的后续代码逻辑。
对应你的代码的修复:
你的过程中修改了AL、BL、CL(对应AX、BX、CX的低8位),违反了上述约定,需在过程开头保存这些寄存器,结尾恢复:
begin increasing; // 保存需要修改的寄存器到栈 push( AX ); push( BX ); push( CX ); // Checking if value2 is greater than value1 mov( value1, AL ); mov( value2, BL ); mov( value3, CL ); cmp( AL, BL ); jge NotIncreasing; // Checking if value3 is greater than value2 cmp( BL, CL ); jge NotIncreasing; // If both conditions are true, it's increasing mov( 1, DX ); jmp Done; NotIncreasing: mov( 0, DX ); Done: // 恢复寄存器 pop( CX ); pop( BX ); pop( AX ); ret();
完整修复后的代码
program IncreasingCheck; #include( "stdlib.hhf" ); static value1: int8; value2: int8; value3: int8; procedure increasing( value1 : int8; value2 : int8; value3 : int8 ); @nodisplay; @noframe; begin increasing; // 保存寄存器 push( AX ); push( BX ); push( CX ); // Checking if value2 is greater than value1 mov( value1, AL ); mov( value2, BL ); mov( value3, CL ); cmp( AL, BL ); jge NotIncreasing; // Checking if value3 is greater than value2 cmp( BL, CL ); jge NotIncreasing; // If both conditions are true, it's increasing mov( 1, DX ); jmp Done; NotIncreasing: mov( 0, DX ); Done: // 恢复寄存器 pop( CX ); pop( BX ); pop( AX ); ret(); end increasing; begin IncreasingCheck; stdout.put( "Enter a value: " ); stdin.get( value1 ); stdout.put( "Enter a value: " ); stdin.get( value2 ); stdout.put( "Enter a value: " ); stdin.get( value3 ); // Call the increasing procedure with parameters push( value3 ); push( value2 ); push( value1 ); call increasing; add( 3, ESP ); // 清理栈参数 // Output result cmp(DX, 1); je Increase; jmp NoInc; Increase: stdout.put( "The values increase!" ); jmp EndProgram; NoInc: stdout.put( "The values don't increase" ); EndProgram: end IncreasingCheck;
内容的提问来源于stack exchange,提问作者Hooray
相关产品推荐
相关产品推荐

